是否可以为我无法更改的类型实现接口(在 C# 预览功能的上下文中:静态抽象接口成员)

Is it possible to implement an interface for a type I can't change (in the context of C#'s preview feature: static abstract interface members)

编辑: 我终于找到了为什么我记得外部接口实现可能是一个功能,这是因为几个月前我一定是在阅读 static abstract interface members proposal at around the same time as this discussion(特别是 “显式实现和消歧” 下的部分)随着时间的推移,这两者在我的脑海中一定已经融合了。

我一直在研究静态抽象接口成员,我想知道是否有可能以某种方式告诉编译器特定类型如何实现特定接口,即使该类型实际上并未实现接口它的声明。即是否可以对外实现接口?

我问这个是因为我记得当我几个月前第一次了解静态抽象接口成员时,这应该是我了解的功能之一,但我找不到这些说法的来源再次(我 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,有没有办法通过现有的乘法运算符在外部实现接口来使其工作?再一次,我记得(可能)视频说这是可能的。

如果您的类型在 class 定义中使用了部分关键字,那么您将能够修改 class,以使用接口。但是如果类型被定义为不可变的,并且不允许 DI 行为,那么简短的回答是否定的。

public interface ISomeInterface
    {
        int DoStuff();
    }

    public partial class TestClass
    {

    }

    public partial class TestClass : ISomeInterface
    {
        public int DoStuff()
        {
            throw new System.NotImplementedException();
        }
    }

或者您可以在 class 上实现一个 DI 接口以允许组合行为。

    public class OtherClass
    {
        private ISomeInterface _someInterface;
        public OtherClass(ISomeInterface someInterface) {
            _someInterface = someInterface;
        }

        public void CalculateStuff()
        {
            _someInterface.DoStuff();
        }
    }

除了这两个选项之外,真的没有办法修改类型,你没有控制权。

这两种方法你应该本能地使用组合。 但是如果我负责的是别人class,你显然没有这个控制权。在这种情况下,无论“DoStuff()”做什么,您都应该创建自己的解决方案。

然后使用组合来允许修改行为,这可能确实允许特定类型的行为存在于您自己的行为旁边。