2012-12-12 23 views

回答

7

沒有在.NET來處理這一個乾淨的方式。泛型不直接支持算術運算。您可以通過變通辦法(如MiscUtils或通過creation of a separate calculator class and delegating the math to it)解決此問題,但這通常會使代碼比兩個實施更復雜。

您可以在內部使用dynamic,這也可以。但是,這會增加(輕微)開銷,這可能會降低此功能的實用性。如果性能是您不想僅支持雙精度數學的主要原因,那麼使用動態可能不是一種選擇。

一種選擇是使用T4來創建一個模板,該模板從單個源文件構建兩個版本的代碼。這將爲您提供完整的本地支持,而不需要開銷(本質上只是爲您編寫兩個類)。

+0

Bah我寫了一個使用動態的整個例子,你的答案將我的水衝出去:(你+1,你贏了這一輪。 –

+1

+1建議T4。 –

0

您可以使用C#泛型此:

using System; 

class Test<T> 
{ 
    T _value; 

    public Test(T t) 
    { 
    // The field has the same type as the parameter. 
    this._value = t; 
    } 

    public void Write() 
    { 
    Console.WriteLine(this._value); 
    } 
} 

class Program 
{ 
    static void Main() 
    { 
    // Use the generic type Test with an int type parameter. 
    Test<int> test1 = new Test<int>(5); 
    // Call the Write method. 
    test1.Write(); 

    // Use the generic type Test with a string type parameter. 
    Test<string> test2 = new Test<string>("cat"); 
    test2.Write(); 
    } 
} 

該博客介紹了它在更詳細一點你http://www.dotnetperls.com/generic

+4

雖然這可行,但你不能用它做很多事情,因爲泛型不支持完整的算術支持。 –

+0

@ReedCopsey這就是爲什麼我希望.NET中的所有數字對象都實現了一個具有所有數學操作的接口。 –

+0

這會有幫助嗎? http://www.codeproject.com/Articles/33617/Arithmetic-in-Generic-Classes-in-C – GracelessROB

相關問題