c# - 允许从接口(interface)转换为实现的通用约束

标签 c# generics constraints

我有一个小类,它实现了一个字典,该字典从接口(interface)类型映射到从基类扩展的该接口(interface)的实现。不幸的是抽象基类没有实现接口(interface),所以一旦在字典中,似乎没有办法将两者联系起来。此类中还有另一种方法依赖于将对象存储为 BaseClass(事实上,我的大部分类都依赖于此——字典中的 getter 有点方便)。

private readonly Dictionary<Type, BaseClass> dictionary;

public void Add<T>(BaseClass base)
{
    if (!(base is T))  // How to get rid of this check?
    {
        throw new ArgumentException("base does not implement " + typeof(T).Name);
    }

    this.dictionary.Add(typeof(T), base);
}

public T Get<T>()
{
    BaseClass base;
    this.dictionary.TryGetValue(typeof(T), out base);
    return (T)(object)base;  // How to get rid of (object) cast?
}

是否有任何巧妙的约束可以用来删除(基数为 T)检查、转换为对象或两者兼而有之?

这里是类设置,供引用:

class BaseClass { }
interface IThing { }
class MyClass : BaseClass, IThing { }

dict.Add<IThing>(new MyClass());
IThing myClass = dict.Get<IThing>();

最佳答案

如果您对要添加的派生类型具有编译类型知识,那么获得您正在寻找的编译时强制执行的唯一方法。

例如,如果您还为要添​​加的类指定了一个类型参数,那么您可以约束该类实现接口(interface)类型参数:

    public void Add<TInterface, TClass>(TClass @base)
        where TClass : BaseClass, TInterface {
        this.dictionary.Add(typeof(TInterface), @base);
    }

所以你可以这样做:

    MyClass ok = new MyClass();
    dict.Add<IThing, MyClass>(ok);

但不是这个:

    class MyClassNotIThing : BaseClass { }

    MyClassNotIThing notOk = new MyClassNotIThing();
    dict.Add<IThing, MyClassNotIThing>(notOk);

除此之外,泛型约束不提供一种方法来约束已知类型(即 BaseClass)从泛型类型参数继承。

关于c# - 允许从接口(interface)转换为实现的通用约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17605663/

相关文章:

c# - ADO.NET + 大量插入 + Excel + C# = "A bad time"吗?

function - 如何在 Rust 的函数和模式匹配中使用泛型?

sql - 多列外键约束

ios - 在 collectionViewCell 中为 imageview 添加约束

c# - 有用的 WPF 实用程序

c# - 使用 Cast<T> 将 int[] 转换为 double[]?

.net - 升级到带有泛型类型参数的 WPF 4 时,来自 InitializeComponent 的 NullReferenceException

java - 在返回所述接口(interface)的通用接口(interface)中创建静态变量(或者至少在 Spring 的映射器中)

c# - F#的静态绑定(bind)约束是如何实现的?

c# - .NET/Windows 窗体 : remember windows size and location