开发者

Check if the typeof(object) in a List is a reference type

this seems odd to me:

if(customerList.Count > 0)
{
   if(typ开发者_如何学Goeof(customerList[0]).IsReferenceType)
   {
      // do what I want
   }
}

How would you do it?


  1. To determine whether the first item in a list is an object of a reference type:

    bool isReferenceType = !(customerList[0] is ValueType);
    
  2. To determine whether a list is a List<T> for some T that is a reference type:

    var listType = customerList.GetType();
    if (!listType.IsGeneric || listType.GetGenericTypeDefinition() != typeof(List<>))
        // It’s not a List<T>
        return null;
    return !listType.GetGenericArguments()[0].IsValueType;
    


You are probably trying to determine the actual type of the generic parameter of a generic collection. Like determining at runtime what is a T of a particular List<T>. Do this:

Type collectionType = typeof(customerList);
Type parameterType = collectionType.GetGenericArguments()[0];
bool isReference = !parameterType.IsValueType;


bool isReferenceType = !(customerList[0] is ValueType);

EDIT

Or are you looking for something like:

bool listIsOfReferenceTypeObjects = !myList.GetType().GetGenericArguments()[0].IsValueType;


ok that worked and I get no exception, when the customerList is empty.

Type collectionType = customerList.GetType();
   Type parameterType = collectionType.GetGenericArguments()[0];
   bool isReference = !parameterType.IsValueType;

@Adesit you get a point because your sample was right except the first line :P

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜