简体   繁体   中英

'System.Type' does not contain a definition for 'GenericTypeArguments' with (dynamic)

I am trying to get the type of a dynamic linq column using

var args = ((dynamic)linqColumn).PropertyType.GenericTypeArguments;

then comparing on the possible types names :

if (args.Length > 0 && args[0].Name == "DateTime")
    ProcessDateTimeType();
else if (args.Length > 0 && args[0].Name == "Double")
    ProcessDoubleType();

This works on a Windows Vista with .NET 4.0, but does not work with a Windows Server 2003 also with .NET 4.0. An error 'System.Type' does not contain a definition for 'GenericTypeArguments' is throwed.

I need GenericTypeArguments only for nullable types.

Any idea ?

Remarks

  • linqColumn is obtained via var linqColumn = linqTableType.GetProperty("COLNAME");
  • linqTableType is obtained via 'Type linqTableType = Type.GetType("MYNAMESPACE." + "TABLENAME");
  • Code is executed inside a web service

As Preston mentioned in the comments, the GenericTypeArguments property was added in .NET 4.5.

4.5 is an in-place upgrade to 4.0; even though you're targeting 4.0, the 4.5 APIs will still work when you use reflection or dynamic .

Try limiting the dynamic code to just the part that retrieves the property type; from that point on, you know the value is a Type , so you can use early binding:

Type propertyType = ((dynamic)linqColumn).PropertyType;

// Visual Studio should now warn you if you try to use:
// var args = propertyType.GenericTypeArguments;

var args = propertyType.IsGenericType && !propertyType.IsGenericTypeDefinition
    ? propertyType.GetGenericArguments()
    : Type.EmptyTypes;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM