如何在C#中确保对象的类型与此相等?

Pat*_*ski 1 c# generics interface type-conversion strong-typing

问题

我有以下界面(可以更改,但只是为了提出想法):

public interface IObj<T>
{
    void Merge(IObj<T> other);
}
Run Code Online (Sandbox Code Playgroud)

问题在于Merge操作.我无法找到确保传递给方法的参数与该类型相同的方法this.例如,看看以下实现:

public class A<T> : IObj<T>
{
    public void Merge(IObj<T> other)
    {
        var casted = other as A<T>;
        if (casted == null)
            throw new ArgumentException("Incorrect type.");

        // do the actual stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

实现接口的任何对象始终需要与相同类型的实例合并.因此,我需要编写这个样板代码,以便在我做任何事之前尝试进行转换.

是否可以通过合同/界面/其他任何方式确保这一点?

Vik*_*ova 5

您可以尝试使用自引用通用模式.它通常用于流畅的可继承对象构建器.

对于你的情况,它应该是这样的:

public interface IObj<T, TSelf> where TSelf : IObj<T, TSelf>
{
    void Merge(TSelf other);
}

class A<T>: IObj<T, A<T>> {
    public void Merge(A<T> alreadyCasted) {

    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这也引入了样板代码(在A类声明中).但是当你在基类的接口中有很多方法时,这很好.

据我所知,没有其他变种.