English 中文(简体)
我怎么能立即获得通用参数类型?
原标题:How can I get an instantiated generic s parameter type?

I m appalled I haven t found anything on the internet about this problem, but probably I m looking for the wrong words. Here is what I need to do.

附录一有一个通用类型:List<string>为简明起见。 我如何获得参数类型(此处为<代码>(指示))?

铭记我需要从通用类别外(而不是在一类方法内,这是我在其他SO问题中所看到的。 底线是,我有一例通用类型,我需要了解其类型和参数类型(如上所示,我谨获得<条码>的类型>和<条码>的类型,而不是<条码>(List<string>>/code>。 当然,这项工作必须在时间进行。

感谢各位回答。

最佳回答
var myList = new List<String>();
var shouldBeString = myList.GetType().GetGenericArguments().FirstOrNull();
var shouldBeGenericList = myList.GetType().GetGenericTypeDefinition();

See http://msdn.microsoft.com/en-us/library/system.type.genericarguments.aspx

问题回答

参看Type.Geteric Arguments(。 您请见有关案例的Type。 它退回了<代码>Type (to Eric Lippert s chagrin

typeof(List<string>).GetGenericArguments()[0]

为什么要赢得你的职能是通用的? 它将让大家了解。

void your_func<T>(List<T> lst)
{
    Type list_type = typeof(List<T>);
    Type generic_list_type = typeof(List<>);
    Type generic_argument_type = typeof(T);
    // do what you need     
}

You can invoke it like normally:

var lst = new List<string>(); 
// ...
obj.your_func(lst);

其他选择是采用其他答复中所述的思考。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签