c# - 如何在 C# 中确保对象的类型等于此?

标签 c# generics interface type-conversion strong-typing

问题

我有以下界面(可以更改,但仅供引用):

public interface IObj<T>
{
    void Merge(IObj<T> other);
}

问题出在 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
    }
}

任何实现接口(interface)的对象总是需要与相同类型的实例合并。因此,我需要在执行任何操作之前编写此样板代码来尝试转换。

问题

是否可以通过契约(Contract)/接口(interface)/其他任何方式来确保这一点?

最佳答案

您可以尝试使用 self-referencing generic pattern . 它通常用于可继承对象的流畅构建器。

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

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) {

    }
}

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

据我所知,没有其他变体。

关于c# - 如何在 C# 中确保对象的类型等于此?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38847933/

相关文章:

c# - 在 C# 上转义花括号和反斜杠

class - 'class' 与 'object' 相关,因为 'interface' 与 ...?

cocoa - 在 Cocoa 中,将私有(private) API 放在 .m 文件中,将公共(public) API 放在 .h 文件中,这是一个好习惯吗?

generics - 如何从泛型方法参数获取java类?

c++ - 扩展 Eigen Ref 类

c# - 如何创建 'Private' ResourceDictionary?

c# - 套接字客户端类的异常与结果代码

c# - gRPC:我应该为整个应用程序使用一个客户端吗?

java - 为什么编译器会对待 List<?> 和 List<?以不同方式扩展 Object>?

c# - 将 BindingSource.DataSource 声明为通用的