2017-09-15 36 views
0

我有一個泛型類,用於定義一系列值。 我想只有一個int類型的方法返回一個在這個範圍內的隨機值。我怎樣纔能有一個在泛型類中的特定類型的方法?它有可能嗎?這裏是我的課:C#中特定類型特定方法的通用類

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; 
    } 
} 
+1

我不知道我是否理解正確,但是你可以派生出一個類'IntRange:Range ',其中你定義了一個'public int GetRandomInRange()'方法。 – Fildor

+0

我想你想在IConvertible,和Covert.changeType – sTrenat

回答

2

剛剛從Range<int>

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

'public void MySpecificToIntMethod()'會更有意義,如果它是'public int MySpecificToIntMethod()';) – Fildor

1

繼承你可以做的亞伊爾哈爾伯施塔特說,或者如果你堅持在你的類中的函數,你可以做這樣的:

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

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>的參數纔會出現此方法。這可能是一個問題,具體取決於你的用例