具有特定于C#中某种类型的方法的泛型类

时间:2017-09-15 08:33:37

标签: c# class generics

我有一个泛型类,用于定义一系列值。 我想有一个只用于int类型的方法,它返回此范围内的随机值。如何在泛型类中使用特定类型的方法?有可能吗?这是我的班级:

public class Range<T> where T : IComparable<T>
{
    public T Minimum { get; set; }
    public T Maximum { get; set; }

    public Range(T Minimum, T Maximum)
    {
        this.Minimum = Minimum;
        this.Maximum = Maximum;
        if (!IsValid())
        {
            this.Minimum = Maximum;
            this.Maximum = Minimum;
        }
    }

    public bool IsValid()
    {
        return this.Minimum.CompareTo(this.Maximum) <= 0;
    }
}

3 个答案:

答案 0 :(得分:2)

只是继承自Range<int>

 public class IntRange : Range<int>
    {
        public IntRange(int Minimum, int Maximum) : base(Minimum, Maximum)
        {
        }
        public void MySpecificToIntMethod()
        {}
    }

答案 1 :(得分:1)

你可以像Yair Halberstadt那样说,或者你坚持在课堂上有这个功能,你可以这样做:

 public class Range<T> where T : IComparable<T>
    {
        public T Minimum { get; set; }
        public T Maximum { get; set; }

        public Range(T Minimum, T Maximum)
        {
            this.Minimum = Minimum;
            this.Maximum = Maximum;
            if (!IsValid())
            {
                this.Minimum = Maximum;
                this.Maximum = Minimum;
            }

        }
        public int GetRandomNumber()
        {
            if (typeof(T) == typeof(int))
            {
                return new Random().Next(Convert.ToInt32(Minimum), Convert.ToInt32(Maximum));
            }
            else
                throw new Exception("Given type is not integer.");
        }
        public bool IsValid()
        {
            return this.Minimum.CompareTo(this.Maximum) <= 0;
        }
    }

以下是 DEMO

答案 2 :(得分:0)

您可以使用静态字段在泛型中的工作方式来指定将用作方法实现的自定义委托:

public class Range<T> where T : IComparable<T>
{
    public T Minimum { get; set; }
    public T Maximum { get; set; }
    // GetRandomNumber specific implementation, the field can have a different value for a specific `T`
    public static Func<Range<T>, T> GetRandomNumberHelper = (self) => throw new NotImplementedException("Not implemented for type " + typeof(T).FullName);
    public T GetRandomNumber()
    {
        return GetRandomNumberHelper(this);
    }

}
public class Program
{
    public static void Main()
    {
        // Assign the delegate in a static constructor or a main
        Range<int>.GetRandomNumberHelper = self => new Random().Next(self.Minimum, self.Maximum);
    }
}

另一种选择是使用某个T的派生类型,如此处的另一个答案所示。问题是,在编译时无法阻止某人创建new Range<int>()而不是new IntRange(),这可能是一个问题,取决于您的用例。

如果您不需要访问随机T的方法,第三种方法是使用扩展方法:

public static class RangeExt
{
    public static int GetRandomNumberHelper(this Range<int> self)
    {
        return new Random().Next(self.Minimum, self.Maximum);
    }
}

这里的问题是,带有Range<T>类型参数的函数将无法访问该方法,只有Range<int>类型的参数才会出现此方法。这可能是一个问题,具体取决于您的用例

相关问题