简体   繁体   English

在C#3.5中获取类型参数受约束的类的类型

[英]Getting type of a type parameter constrained class in C# 3.5

I'm trying to get the type of a custom class to which I don't have access to editing and it has a parameter type constraint on its declaration. 我正在尝试获取自定义类的类型,该类无权进行编辑,并且其声明具有参数类型约束。 Just like this: 像这样:

public class GenericItemCollection<T> where T : System.IEquatable<T>
{
    public GenericItemCollection();
    public GenericItemCollection(string json);

    public int Count { get; }
    public List<T> Created { get; }
    public List<T> Current { get; }
    public List<T> Deleted { get; }
    public List<T> Original { get; }
    public List<T> Updated { get; }

    public void AcceptChanges();
    public void AddItem(T item);
    public void BindItem(T item);
    public void DeleteItem(T item);
    public void UpdateItem(T item);
}

} }

So what I want is the type GenericItemCollection when T is actually something. 所以我想要的是当T实际上是某种东西时的GenericItemCollection类型。 Ie: 即:

private void MyMethod<T>(GenericItemCollection<T> genericList){
    Type listType = typeof(GenericItemCollection<typeof(T)>);
    //...
}

which will be called as such: 可以这样称呼:

MyMethod<Foo>(fooGenericList);
MyMethod<Bar>(barGenericList);

In that case, I want listType to be 在这种情况下,我希望listType为

GenericItemCollection<Foo> 

and

GenericItemCollection<Bar> 

I know typeof(T) won't exist before runtime but it should return a Type regardless but VS just says "Type expected" on 我知道typeof(T)在运行时之前将不存在,但是无论如何它都应该返回一个Type,但是VS只会在“

GenericItemCollection<typeof(T)> 

I'm not all that proficient using Generics, so I'm obviously missing something and I'd like you guys to point out what that is. 我不太熟练使用泛型,因此我显然缺少一些东西,我希望你们指出那是什么。 Many thanks. 非常感谢。

First of, whatever constraint is applied to the generic type parameter of GenericItemCollection must also be applied to the generic type parameter of MyMethod 首先,无论对GenericItemCollection的泛型类型参数应用什么约束,也必须对MyMethod的泛型类型参数应用

private void MyMethod<T>(GenericItemCollection<T> genericList) where T: IEquatable<T>

Then, just replace typeof(T) with T 然后,只需将typeof(T)替换为T

Type listType = typeof(GenericItemCollection<T>);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM