【问题标题】:'System.Type' does not contain a definition for 'GenericTypeArguments' with (dynamic)“System.Type”不包含“GenericTypeArguments”的定义(动态)
【发布时间】:2015-09-17 16:44:39
【问题描述】:

我正在尝试使用

获取动态 linq 列的类型
var args = ((dynamic)linqColumn).PropertyType.GenericTypeArguments;

然后比较可能的类型名称:

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

这适用于带有 .NET 4.0 的 Windows Vista,但不适用于带有 .NET 4.0 的 Windows Server 2003。抛出错误'System.Type' does not contain a definition for 'GenericTypeArguments'

我只需要可空类型的 GenericTypeArguments。

有什么想法吗?

备注

  • linqColumn 是通过var linqColumn = linqTableType.GetProperty("COLNAME"); 获得的
  • linqTableType 是通过'Type linqTableType = Type.GetType("MYNAMESPACE." + "TABLENAME"); 获得的
  • 代码在里面执行 网络服务

【问题讨论】:

  • msdn.microsoft.com/en-us/library/… - 在 Windows Server 2003 SP2 上受支持 - 检查您是否安装了 SP2
  • GenericTypeArguments 直到 .Net 4.5 才添加到 System.Typemsdn.microsoft.com/en-us/library/…
  • 实际上是的 Preston 是对的,我正在查看 GetGenericArguments - 你确定你是在 Vista 上为 .NET 4.0 构建吗?
  • 该项目使用 VWD 2010 Express,目标框架是 .NET Framework 4。但是我刚刚注意到 Microsoft .NET Framework 4.5.1 安装在 Vista 上,但没有安装在 Windows Server 2003 上。这可能是错误的根源,尽管该项目仅针对 .NET 4?

标签: c# linq dynamic reflection


【解决方案1】:

正如 Preston 在 cmets 中提到的,GenericTypeArguments 属性是在 .NET 4.5 中添加的。

4.5 是对 4.0 的就地升级;即使您的目标是 4.0,当您使用反射或 dynamic 时,4.5 API 仍然可以工作。

尝试将dynamic 代码限制为仅检索属性类型的部分;从那时起,您知道该值为Type,因此您可以使用早期绑定:

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;

【讨论】:

  • 谢谢,因为只需要可空类型(Nullable``1 DateTime, ...),所以使用Nullable.GetUnderlyingType(linqColumn.PropertyType) 也可以。
猜你喜欢
  • 1970-01-01
  • 2015-11-27
  • 1970-01-01
  • 2018-05-28
  • 1970-01-01
  • 1970-01-01
  • 2017-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多