【问题标题】:Generic method with implicit cast to Guid隐式转换为 Guid 的通用方法
【发布时间】:2013-05-03 13:01:29
【问题描述】:

我实际上有一种从 Feature 对象的特殊数据行中读取值的方法:

    private static T GetRowValueByMethod<T>(Feature feature, string fieldName)
    {
        return (T) feature.GetDataRow(fieldName)[fieldName];
    }

这对大多数值都适用,但使用Guid 我有问题。如果该字段包含System.Guid 对象,那么一切都很好。但是如果它包含一个字符串值,那么我会得到一个错误,因为 Guid 不能从字符串隐式转换。

要从字符串中获取Guid 对象,需要通过 Guid 构造函数创建一个新的 Guid 对象。 但是这里不允许返回 Guid 对象。 无法创建新的 T 对象。 创建Guid 对象并转换为T 也是不可能的。那么该怎么办呢?

我尝试过类似的方法,但这不起作用(注意:假代码)

    private static T GetRowValueByMethod<T>(Feature feature, string fieldName)
    {
        var obj = feature.GetDataRow(fieldName)[fieldName];
        if (obj.ToString().IsAGuid())
        {
            return (T) new Guid(obj.ToString());
        }

        return (T) obj;
    }

有人对此有好的解决方案吗?

【问题讨论】:

    标签: c# generics guid


    【解决方案1】:

    您正在尝试将Guid 转换为T。这不可能发生,因为没有从GuidT 的转换。如果您首先将Guid 值放入object,它将起作用。

    试试这个:

    private static T GetRowValueByMethod<T>(Feature feature, string fieldName)
    {
        object obj = feature.GetDataRow(fieldName)[fieldName];
        if (obj.ToString().IsAGuid())
            obj = new Guid(obj.ToString());
        return (T)obj;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多