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?


Use a literal.

.aspx:

<asp:Literal runat="server" ID="myLiteral" />

codebehind:

myLiteral.Text = "<h2> this is a h2 html tag</h2>";

this will print out

This is a h2 html tag

4

3 回答 3

2

好吧,您有is关键字,可以比较对象

if(myObject is MyClass)
    doStuff();

你也有

typeof(myObject);

正如LB所说,你有

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

如果对象类型不是您的方法的泛型参数之一,那么您可以使用返回泛型类型参数类型的Type.GetGenericArguments方法(在您的情况下为 List)。

否则,如果对象类型是您方法的通用参数之一,则使用 Travis J 的答案。

于 2012-11-13T22:28:55.383 回答
1

给定

List<T> objects;

你可以得到这样的类型

var objType = typeof(T);
于 2012-11-13T19:49:06.957 回答