編輯:我終于找到了為什么我記得外部介面實作可能是一個特性,這是因為幾個月前我一定在閱讀靜態抽象介面成員提案的同時進行了討論(特別是在“明確的實施和消歧”)隨著時間的推移,這兩者在我的腦海中一定已經融合了。
我一直在使用靜態抽象介面成員,我想知道是否有可能以某種方式告訴編譯器特定型別如何實作特定介面,即使該型別實際上并未在其宣告中實作介面。也就是說,是否可以在外部實作介面?
我問這個是因為我記得幾個月前我第一次了解靜態抽象介面成員時,這應該是我學到的功能之一,但我再也找不到這些說法的來源(我90% 確定這是一個 youtube 視頻)。
這有沒有計劃過?它會被實施嗎?
我的意思的一個例子:
public struct Point2D :
IAdditionOperators<Point2D, Point2D, Point2D>,
ISubtractionOperators<Point2D, Point2D, Point2D>
{
public float X, Y;
public static Point2D operator (Point2D left, Point2D right) => new() { X = left.X right.X, Y = left.Y right.Y };
public static Point2D operator - (Point2D left, Point2D right) => new() { X = left.X - right.X, Y = left.Y - right.Y };
public static Point2D operator * (Point2D point, float multiplier) => new() { X = point.X * multiplier, Y = point.Y * multiplier };
}
public static TInterpolated LinearInterpolation<TInterpolated, TTime>(TInterpolated start, TInterpolated end, TTime interpolation)
where TTime : INumber<TTime>
where TInterpolated :
IAdditionOperators<TInterpolated, TInterpolated, TInterpolated>,
ISubtractionOperators<TInterpolated, TInterpolated, TInterpolated>,
IMultiplyOperators<TInterpolated, TTime, TInterpolated>
{
interpolation = TTime.Clamp(interpolation, TTime.Zero, TTime.One);
return start (end - start) * interpolation;
}
public static class SomeClass
{
public static Point2D SomeMethod(Point2D startingPoint, Point2D goalPoint, float time)
{
Point2D lerpedPoint = LinearInterpolation(startingPoint, goalPoint, time);
return lerpedPoint;
}
}
在SomeMethod()中,會出現錯誤,因為即使它實作了介面所需的運算子,Point2D也沒有實作。IMultiplyOperators<Point2D, float, Point2D>
現在,說我不能改變Point2D,有沒有辦法讓我通過已經存在的乘法運算子在外部實作介面來使其作業?再一次,我記得(可能)視頻說這是可能的。
uj5u.com熱心網友回復:
如果您擁有的型別在類定義中使用 partial 關鍵字,那么您將能夠修改類以使用介面。但是如果型別被定義為不可變,并且不允許 DI 行為,那么簡短的回答是否定的。
public interface ISomeInterface
{
int DoStuff();
}
public partial class TestClass
{
}
public partial class TestClass : ISomeInterface
{
public int DoStuff()
{
throw new System.NotImplementedException();
}
}
或者,您可以在類上實作 DI 介面以允許組合行為。
public class OtherClass
{
private ISomeInterface _someInterface;
public OtherClass(ISomeInterface someInterface) {
_someInterface = someInterface;
}
public void CalculateStuff()
{
_someInterface.DoStuff();
}
}
在這兩個選項之外,真的沒有辦法修改型別,你無法控制。
在這兩種方法中,您應該本能地使用組合。但是如果由其他人負責上課,你顯然沒有這個控制權。在這種情況下,您應該為“DoStuff()”所做的任何事情創建自己的解決方案。
然后使用組合來允許修改行為,這可能確實允許特定型別的行為存在于您自己的旁邊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/449178.html
上一篇:如何在C#中使方法泛型?
