虽然 Stackoverflow 中也有类似的问题,但这对我的问题没有帮助。 这是我正在做的事情的大图。我正在为我的 iDB2DataReader 生成 IL,以动态地从数据库获取我的类型并映射到我的 poco。 我在获取可空值以提取数据时遇到问题。
所以我有一个方法需要通过反射返回methodinfo。为了得到这个,我使用了我需要的类型的“getmethod”。 这是代码:
private static MethodInfo GetDataMethod(Type destinationDataType, Type underlyingDestinationDataType, iDB2DataReader reader)
{
MethodInfo methInfo = null;
if (_readerDataMethods.ContainsKey(destinationDataType))
{
methInfo = _readerDataMethods[destinationDataType];
}
else
{
if (underlyingDestinationDataType != null)
{
//trying to get underlying type which would be DateTime thus resulting in GetDatetime.
methInfo = reader.GetType().GetMethod("Get" + underlyingDestinationDataType.Name);
}
else
methInfo = reader.GetType().GetMethod("Get" + destinationDataType.Name);
//methInfo = reader.GetType().GetMethod("Get" + destinationDataType.ToGenericTypeString());
if (methInfo != null)
{
_readerDataMethods[destinationDataType] = methInfo;
}
}
return methInfo;
}
正如您从我的代码注释中看到的那样,我得到了 datetime 的基础类型,但这不起作用,它收到运行时错误“Operation could destabilize the runtime.”。
真正的问题是我不知道应该为 Nullable<DateTime>
的 getmethod 使用什么名称.或者至少我希望事情就是这么简单。任何帮助将不胜感激。
最佳答案
您可能必须创建一个特殊情况 fur Nullables,因为实际类型名称在方法名称中无效。我会检查它是否是 Nullable 类型,并使用反射来获取通用参数。
例子:
Type t = typeof (Nullable<DateTime>);
Console.WriteLine(t.Name); // Nullable`1
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
{
Type t2 = Nullable.GetUnderlyingType(t);
Console.WriteLine("Nullable"+t2.Name); // NullableDateTime
}
关于c# - 反射 - 可空 <datetime> 的 get 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12058697/