【问题标题】:Returning null for generic type extension in c#在 c# 中为泛型类型扩展返回 null
【发布时间】:2018-06-18 04:51:47
【问题描述】:

我创建了一个扩展函数,它将字符串作为输入并检查值并基于通用类型,将其转换为目标类型并返回它,它运行良好。

现在的问题是,如果我将输入值作为空传递,它应该返回 null,对于可为空的类型,但它只是抛出异常。

例如:如果我想将它转换为日期时间,它会抛出以下异常:

String was not recognized as a valid DateTime

下面是我的代码:

public static class Extension
    {
        public static T ToNull<T>(this string value)
        {
            var stringType = "System.Nullable`1[[System.{0}, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]";

            if (typeof(T) == typeof(String))
                stringType = string.Format(stringType, "String");
            if (typeof(T) == typeof(Int32?) || typeof(T) == typeof(Int32))
                stringType = string.Format(stringType, "Int32");
            if (typeof(T) == typeof(DateTime?) || typeof(T) == typeof(DateTime))
                stringType = string.Format(stringType, "DateTime");
            if (typeof(T) == typeof(Int64?) || typeof(T) == typeof(Int64))
                stringType = string.Format(stringType, "Int64");


            Type originalType = Type.GetType(stringType);
            var underlyingType = Nullable.GetUnderlyingType(originalType);
            return (T)Convert.ChangeType(value, underlyingType ?? originalType);
        }
    }

这里是我如何访问它:

string s = "";
DateTime? t = s.ToNull<DateTime?>();
Console.WriteLine(t);

对于上述情况,我想返回 null。

【问题讨论】:

  • 如果你打算像这样使用typeof,为什么不写单独的方法呢? ToNullableDateTime 等?
  • 这个问题让人困惑
  • @mjwills,因为我要处理多种类型,所以我需要一个通用函数,您能否提出一种更好的方法来在单个函数中处理多种类型?
  • 我不会在单个函数中执行此操作。我会使用多种功能。这种方法的问题是不可能知道支持哪些类型(例如,我不能用byte? 调用它,但是如果不深入研究函数本身的细节就不可能知道)。多个功能解决了这个问题。

标签: c# asp.net generics extension-methods nullreferenceexception


【解决方案1】:

那么就返回default

//Check for empty or null first
if(string.IsNullOrEmpty(value)) return default(T);

//Then your code
var stringType = "System.Nullable`1[[System.{0}, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]";
...

【讨论】:

    【解决方案2】:

    为了回答@mjwills 关于创建单独方法的回复,我找到了一个解决方案来保持它的单一方法,并且仍然动态地处理你扔给它的任何类型。

    public static class Extension
    {
        public static T ToNull<T>(this string value)
        {
            if (String.IsNullOrEmpty(value)) return default(T);
            Type originalType = typeof(T);
            var underlyingType = Nullable.GetUnderlyingType(originalType);
            return (T)Convert.ChangeType(value, underlyingType ?? originalType);
        }
    }
    

    【讨论】:

    • Type.GetType(typeof(T).FullName) 毫无意义。只需使用typeof(T)
    猜你喜欢
    • 2013-10-18
    • 2014-09-08
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 2018-07-13
    相关资源
    最近更新 更多