c# - 返回可空类型值的通用方法

标签 c# nullable generic-programming

I wrote below method with follwing requirement -

  1. 输入的是xmlnode和attributeName
  2. 如果找到与传递的关联属性名称相关联的值,则返回该值
  3. 如果传递的 attributeName 中没有值,它应该返回 -

    3.1。对于整数 -1 3.2.对于日期时间 DateTime.MinValue 3.3.对于字符串,空 3.4.对于 bool,null

对于情况 3.4,以下方法失败。

public T AttributeValue<T>(XmlNode node, string attributeName)  
        {
            var value = new object();

            if (node.Attributes[attributeName] != null && !string.IsNullOrEmpty(node.Attributes[attributeName].Value))
            {
                value = node.Attributes[attributeName].Value;
            }
            else
            {

                if (typeof(T) == typeof(int))
                    value = -1;
                else if (typeof(T) == typeof(DateTime))
                    value = DateTime.MinValue;
                else if (typeof(T) == typeof(string))
                    value = null;
                else if (typeof(T) == typeof(bool))
                    value = null;



            }
            return (T)Convert.ChangeType(value, typeof(T));
        }

当把这个改成

public System.Nullable<T> AttributeValue<T>(XmlNode node, string attributeName) where T : struct 
        {
            var value = new object();

            if (node.Attributes[attributeName] != null && !string.IsNullOrEmpty(node.Attributes[attributeName].Value))
            {
                value = node.Attributes[attributeName].Value;
            }
            else
            {

                if (typeof(T) == typeof(int))
                    value = -1;
                else if (typeof(T) == typeof(DateTime))
                    value = DateTime.MinValue;
                else if (typeof(T) == typeof(string))
                    return null;
                else if (typeof(T) == typeof(bool))
                    return  null;



            }
            return (T?)Convert.ChangeType(value, typeof(T));
        }

It fails for string type i.e. case 3.3

期待一些帮助。

最佳答案

对于 3.4,您需要使用 bool? 作为 T 的类型,这样您就可以返回 null。

然后你可以为 3.3 和 3.4(string 和 bool?)使用 default 关键字。根据 msdn它将为引用类型返回 null 并为值类型(如 int 或 bool)返回默认值。

你可以这样使用它

return default(T);

关于c# - 返回可空类型值的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17363937/

相关文章:

javascript - 如何在 Selenium C# 中切换 Chrome 上的标签页?

c# - 将 Guid 转换为可为空的 Guid

C 代码 : Passing expression as an argument in recursion call

C++ 隐式/显式模板方法特化问题

c# - 我什么时候需要管理托管资源?

c# - 泛型只允许整数作为类型参数

c# - Linqpad 6 (Core) 和.Net Core Api?

c# - 如何使用可空的 setter/getter ?

generics - Kotlin 类型与泛型不匹配

generic-programming - 如何实现通用 Kafka Streams 反序列化器