是否有人能指向我需要實現的接口,以獲得基本的數學運算符(即+, - ,*,/)以在自定義類型上運行?在自定義C#類型中實現數學函數?
3
A
回答
17
public struct YourClass
{
public int Value;
public static YourClass operator +(YourClass yc1, YourClass yc2)
{
return new YourClass() { Value = yc1.Value + yc2.Value };
}
}
2
您需要重載該類型的運算符。
// let user add matrices
public static CustomType operator +(CustomType mat1, CustomType mat2)
{
}
3
你可以找到操作的重載自定義類型here一個很好的例子。
public struct Complex
{
public int real;
public int imaginary;
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
// Declare which operator to overload (+), the types
// that can be added (two Complex objects), and the
// return type (Complex):
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}
}
5
public static T operator *(T a, T b)
{
// TODO
}
等了其他運營商。
2
你正在尋找的不是一個接口,而是Operator Overloading。一起
public static MyClass operator+(MyClass first, MyClass second)
{
// This is where you combine first and second into a meaningful value.
}
之後,您可以添加MyClasses:基本上,你定義一個靜態方法,像這樣
MyClass first = new MyClass();
MyClass second = new MyClass();
MyClass result = first + second;
1
這是運營商和壓倒一切的MSDN文章在C#:http://msdn.microsoft.com/en-us/library/s53ehcz3(loband).aspx
相關問題
- 1. Haskell自定義數學類型和類
- 2. 解析自定義類型的數學函數
- 3. 重載自定義類型的標準數學函數
- 4. 如何在QT中爲自定義模型實現removeRow()函數?
- 5. C#數學類型的數學類型?
- 6. 自定義丟失函數的實現
- 7. 如何在python中爲自定義數據實現next_batch()函數
- 8. 將自定義C++類型傳遞爲QML函數參數
- 9. 在Prolog中定義(數學)函數
- 10. 如何使用自定義類型的函數指針在C++
- 11. 在C#中實現函數
- 12. 實現自定義休眠類型
- 13. 列表實現和自定義類型
- 14. 在C#實現併發安全的自定義數據類型的
- 15. C++從函數返回自定義類
- 16. C#自定義數據類型!
- 17. C自定義數據類型
- 18. 創建自定義數據類型C++
- 19. 自定義數據類型C
- 20. 自定義類型在C#
- 21. C#自定義複選框+自定義綁定數據類型
- 22. pow函數在C中定義和實現在哪裏?
- 23. Python - 如何實現與NumPy函數兼容的自定義類?
- 24. netbeans可以學習類的php自定義函數參數嗎?
- 25. 如何實現共享自定義數據類型
- 26. 在VB.Net中實現自定義GroupBy函數
- 27. 在stringtemplate v4中實現自定義函數
- 28. 自定義getLine()函數c
- 29. 自定義MySQL函數類
- 30. 自定義函數類
一般,如果你正在做運算符重載,你可能正在處理什麼是值類型而不是需要(可能)成爲其他類型的基類的引用類型,所以你應該考慮使用一個結構而不是一個類來基礎類型。 – 2009-10-08 14:22:27
查爾斯,謝謝你的建議,我忽略了它。我編輯了代碼。 – 2009-10-08 14:26:14