[英]C# interface to check type T has an operator / A way to check if type T has an operator
interface IMathable
{
public static IMathable operator +(IMathable l, IMathable r);
public static IMathable operator -(IMathable l, IMathable r);
}
有可能嗎? 我有數學課。 Vector2 / 3/4/5/6 Matrix3x3 / 4x4 / 5x5 / 6x6等。
他們沒有共同的職業。 但是它們都有運算符,例如+-* /
我想上一堂課。
class MyClass <T> where T : IMathable
{
T magnitude_required_to_reach_toHere;
public MyClass (IMathable from, IMathable toHere)
{
magnitude_required_to_reach_toHere = from + toHere;
}
}
有沒有辦法做到這一點? 建議我讓我所有的數學課都從抽象類繼承,但是我不能為所有這些數學類都提供抽象類,因為它們是內置的,屬於庫的一部分。 我無法修復代碼。
據我所知,您不能在接口上定義運算符。
但是運算符或多或少是語法糖。
您可以定義:
interface IMathable {
IMathable add (IMathable other);
IMathable sub (IMathable other);
}
實際上,運算符或多或少是一個方法,但是該方法的標識符( +
和-
)以及編譯器維護符號表並找出合適的運算符本身的地方。
編輯 :您要的是不可能的。 特別是因為IMathable
無法知道假定的返回類型應該是什么。
但是,有一些解決方法可以通過使用一些函數式編程來解決:
class MyClass <T> {
T magnitude_required_to_reach_toHere;
public MyClass (T from, T toHere, Func<T,T,T> addfunction) {
magnitude_required_to_reach_toHere = addFunction(from,toHere);
}
}
因此,您將一個函數作為參數傳遞,該函數必須具有如何解決問題的計算知識。 例如,如果T
是整數:
MyClass<int> mc = new MyClass<int>(5,7,(x,y) => x+y);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.