【问题标题】:How to write a generic conversion method which would support converting to and from nullable types? [duplicate]如何编写一个支持与可空类型相互转换的通用转换方法? [复制]
【发布时间】:2012-04-04 02:05:06
【问题描述】:

可能重复:
How can I fix this up to do generic conversion to Nullable<T>?

public static class ObjectExtensions
    {
        public static T To<T>(this object value)
        {
            return (T)Convert.ChangeType(value, typeof(T));
        } 
    }

我上面的扩展方法有助于将一种类型转换为另一种类型,但它不支持可为空的类型。

例如,{0} 工作正常,但 {1} 不工作:

{0}:
var var1 = "12";
var var1Int = var1.To<int>();

{1}:
var var2 = "12";
var var2IntNullable = var2.To<int?>();

那么,如何编写一个支持与可空类型相互转换的通用转换方法?

谢谢,

【问题讨论】:

  • 你试过Nullable&lt;int&gt;吗?
  • @MrLister,您不能在泛型方法中指定类型。

标签: c# generics extension-methods type-conversion


【解决方案1】:

这对我有用:

public static T To<T>(this object value)
{
    Type t = typeof(T);

    // Get the type that was made nullable.
    Type valueType = Nullable.GetUnderlyingType(typeof(T));

    if (valueType != null)
    {
        // Nullable type.

        if (value == null)
        {
            // you may want to do something different here.
            return default(T);
        }
        else
        {
            // Convert to the value type.
            object result = Convert.ChangeType(value, valueType);

            // Cast the value type to the nullable type.
            return (T)result;
        }
    }
    else 
    {
        // Not nullable.
        return (T)Convert.ChangeType(value, typeof(T));
    }
} 

【讨论】:

  • 好,TA。只有一点;它不仅仅是可以为空的值类型,例如约会时间? (据我所知,DateTime 本身就是一个引用类型)所以您的代码 cmets 可能需要更正;)
  • no - DateTime 是一个值类型,因为它是一个结构。只有类是 .NET 中的引用类型
  • 你是对的!应该已经检查过了!
  • 一些小的压区和褶皱会使该方法更短。
猜你喜欢
  • 1970-01-01
  • 2011-01-22
  • 2014-01-15
  • 2016-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-02
相关资源
最近更新 更多