c# - 反射 - 可空 <datetime> 的 get 方法

标签 c# reflection db2

虽然 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/

相关文章:

c# - Xamarin在Sqlite中存储日期的格式是什么?

java - hibernate :在运行时创建实体(带注释)

scala - 在 Scala 中调用反射案例类构造函数

java - 访问构造的注释参数进行修改

db2 - DB2 中的确定性函数

c# - 温莎城堡 : Register generics with more than one items

c# - 用于单元测试的 ControllerContext.HttpContext 初始化

c# - 如何在 AX 查询服务中格式化 DateTime 比较值

sql - 是否可以在 DB2 的时间戳列中显式插入值

stored-procedures - pyodbc 从使用 DB2 的存储过程返回多个游标