C# Reflection: How to get the type of a Nullable?

后端 未结 5 1342
面向向阳花
面向向阳花 2021-01-01 11:04

What I want to do is something like this:

switch( myObject.GetType().GetProperty( \"id\") )
{
    case ??: 
        // when Nullable, do this
           


        
5条回答
  •  耶瑟儿~
    2021-01-01 11:24

    The question is very confusing. Is "myObject" the object that might be a nullable int? Or is the property "id" possibly of type nullable int?

    If the former, your question cannot be answered because it presupposes a falsehood. There is no such thing as a boxed nullable int. I note that all of the answers which propose if (myobject.GetType() == typeof(int?)) are therefore incorrect; the condition will never be true.

    When you convert a nullable int to object, either it becomes a null reference (if the nullable int had no value) or it becomes a boxed int. There is no way to determine if an object contains a nullable int because an object never contains a nullable int.

    If the latter, compare the property type to typeof(int?). You cannot use a switch; only constants may be used for switch cases and types are not constants.

    All that said, this is a bad code smell. Why are you using reflection in the first place?

提交回复
热议问题