在C#中创建一个类型为“Type”的对象类型的对象

时间:2012-04-23 09:48:03

标签: c# collections

我是C#的新手,我有以下问题:

我需要创建一个继承自Collection的TypeCollection,这里的对象类型是我创建的一些类型。

在InsertItem()重载方法中,我想检查对象是否来自我创建的特定类型层次结构,否则我抛出异常。

附上了代码段:

public class ObjectTypeCollection<Type> : Collection<Type>
{
    protected override void InsertItem(int index, Type item)
    {   
        if(!(Utility.IsFDTObject(item.GetType())))
        {          
            throw new ArgumentException(string.Format("Type {0} is not valid", item.ToString()));
        }
        base.InsertItem(index, item);
    }
}

这里的问题是项目实例。它没有任何方法可以让我获得当前传递的Type。 GetType()不会返回我传递的类型。目前,我使用过:

System.Type typ = System.Type.GetType(item.ToString()); 

获取类型,然后将其传递给Utility方法。这很好用。这是正确的做法吗?

你能帮我吗?

4 个答案:

答案 0 :(得分:1)

您可以在类型参数Type上设置约束,请参阅此处:http://msdn.microsoft.com/en-us/library/d5x73970(v=vs.80).aspx

这是静态检查,您不需要像目前那样做任何动态的事情。具体做法是:

public class ObjectTypeCollection<T> : Collection<T> where T : <base class name>

答案 1 :(得分:0)

您可以使用Type.IsAssignableFrom检查是否可以从另一个类型的实例(如果它们兼容)分配Type的实例。像这样:

if (typeof(FDTObject).IsAssignableFrom(item))

但你的问题有点不清楚。也许您不想插入实际类型,而是插入特定类型的对象,并能够使用不同类型实例化Collection?然后你可以约束你的类中的泛型参数:

public class ObjectTypeCollection<T> : Collection<T> where T: FDTObject

或者您只想要一个集合,其中所有对象都是FDTObject或它的后代。然后你可以使用List<FDTObject>并进行即时静态类型检查(如果你得到的话就是最好的解决方案):

List<FDTObject> fdtList = new List<FDTObject>();

对我来说,现在还不太清楚。是否要将System.Type的实例添加到集合中(那么您需要在类名后直接删除第一个泛型参数)?或者您刚刚选择Type作为您的通用参数的名称(这是一个糟糕的选择,因为已经有一个类型,即System.Type这样命名?)

答案 2 :(得分:0)

使用Type.IsAssignableFrom方法:

public class FDTObject {}
public class MyDTObject1 : FDTObject {}
public class MyDTObject2 : FDTObject { }

public class ObjectTypeCollection : Collection<Type>
{
    protected override void InsertItem(int index, Type item)
    {
        if (!typeof(FDTObject).IsAssignableFrom(item))
        {
            throw new ArgumentException(string.Format("Type {0} is not valid", item));
        }
        base.InsertItem(index, item);
    }
}

用法:

var collection = new ObjectTypeCollection();  
collection.Add(typeof(MyDTObject1)); // ok  
collection.Add(typeof(MyDTObject2)); // ok  
collection.Add(typeof(String)); // throws an exception  

答案 3 :(得分:0)

除非我误解你的想法,否则你不能只使用generic list吗?

您可以使用设置为基类的type参数初始化列表:

var list = new List<FDTObject>(); // assuming this is one of your base classes based upon your example.

然后,您可以将任何对象添加到FDTObject或继承自FDTObject

的列表中