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_Stack Overflow中文网
Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
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
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
好吧,您有is关键字,可以比较对象
is
if(myObject is MyClass) doStuff();
你也有
typeof(myObject);
正如LB所说,你有
obj.GetType() too
如果对象类型不是您的方法的泛型参数之一,那么您可以使用返回泛型类型参数类型的Type.GetGenericArguments方法(在您的情况下为 List)。
否则,如果对象类型是您方法的通用参数之一,则使用 Travis J 的答案。
给定
List<T> objects;
你可以得到这样的类型
var objType = typeof(T);