1

I am looking to create a generic method that receives a List. I need to determine what the object is within the list so that I can then do the necessary work according to the object that is being passed in within the list. How can I determine the kind of object that the List contains?


well you have the is keyword, which can compare objects

if(myObject is MyClass)
    doStuff();

you also have

typeof(myObject);

and as L.B. said, you have

obj.GetType() too
4

3 に答える 3

2

isオブジェクトを比較できるキーワードがあります

if(myObject is MyClass)
    doStuff();

あなたも持っています

typeof(myObject);

そしてLBが言ったように、あなたは持っています

obj.GetType() too
于 2012-11-13T19:48:43.683 に答える
1

given

List<T> objects;

you can get the type like this

var objType = typeof(T);
于 2012-11-13T19:49:06.957 に答える
1

If the object type is not one of the generic parameters of your method then you can use the Type.GetGenericArguments method that returns the types of the parameters of a generic type (in your case List).

Else if the object type is one of the generic parameters of your method then use Travis J's answer.

于 2012-11-13T22:28:55.383 に答える