约束公共财产的具体类型的列表与LT;类型> [英] Constrain public property to specific types in List<Type>

查看:110
本文介绍了约束公共财产的具体类型的列表与LT;类型>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我原来的问题将是基本相同约束型特定类型

My original question was going to be basically identical to Constrain type to specific types.

我所希望实现的基本上这是

What I am looking to accomplish is basically this.

public List<Type> MyPublicProperty { get; set; } where T IMyCustomInterface

现在阅读了上面的问题,我可以看到它显然是不可能的。

Now reading the above question I can see it is obviously not possible.

为了让你的上下文我建立,旨在支持多种类型的解析器的想法(前提是他们实现一个特定的接口),但我做出任何编译型假设什么数据类型可能被解析。它是简单地设置有支持的类型的列表,并应能自动地制定出其余部分。

To give you an idea of context I am building a parser that is designed to support multiple types (provided they implement a specific interface) but I make no compile type assumptions about what datatypes it might be parsing. It is simply to be provided with a list of supported types and should be able to automagically work out the rest.

所以基本上我想知道是什么,是替代(除了当该属性设置运行时类型检查)这样的属性(如果有的话)?

So basically what I am wondering is what is the alternative (besides runtime type checking when the property is set) for such a property (if any exist)?

编辑:建议的解决方案似乎并没有工作。

The suggested solution doesn't appear to work.

我最终的代码看起来像这样:

I end up with code that looks like this:

public class CustomSerializableTypeList<T> : List<T> where T : ITcpSerializable
{

}

CustomSerializableTypeList<Type> myCustomTypes = new CustomSerializableTypeList<Type>();

和收到以下错误:

类型的System.Type'不能使用
在通用
型或方法
位CustomSerializableTypeList类型参数T。有
是'的System.Type'到
'ITcpSerializable'没有隐式引用转换

The type 'System.Type' cannot be used as type parameter 'T' in the generic type or method 'CustomSerializableTypeList'. There is no implicit reference conversion from 'System.Type' to 'ITcpSerializable'.

错误非常有意义,有一次我看,想想已经提出了泛型的实现。

The error makes perfect sense once I look at and think about the generics implementation that has been suggested.

有必须解决的办法。

推荐答案

我想你需要自己的列表实现,是要包装一个列表<类型> 。也许是这样的:

I reckon you would need your own list implementation that is going to wrap a List<Type>. Maybe something like this:

public class TypeList<T> where T : class
{
    private readonly List<Type> list = new List<Type>();

    public void Add(Type item)
    {
        if(!typeof(T).IsAssignableFrom(item))
        {
            throw new InvalidOperationException();
        }

        list.Add(item);
    }
}



当然,你可能会想实施的IList<类型方式> ,然后简单地委托方法的列表

Of course you would probably want to implement IList<Type> and then simply delegate the methods to the list.

这篇关于约束公共财产的具体类型的列表与LT;类型&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆