如何实现与Nullable< T>相同的方法。 T可以为空? [英] How can I achieve the same as Nullable<T> where T is nullable?

查看:68
本文介绍了如何实现与Nullable< T>相同的方法。 T可以为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到这个问题听起来很愚蠢,但请耐心等待。我有一个这样的课:

I realize this question sounds stupid, but please bear with me. I have a class like this:

public class DropDownListViewModel<TScalar>
{
    private bool _valueIsSet;
    private TScalar _value;
    //private Nullable<TScalar> _nullableValue;
    private SelectList _selectList;

    public SelectList SelectList
    {
        get
        {
            return _selectList;
        }
        set
        {
            _selectList = value;
            if (_valueIsSet)
            {
                _selectList.SetSelected(_value);
            }
        }
    }
}



我发现使用 _valueIsSet 笨拙而且更喜欢 Nullable< TScalar> 其中 Nullable 如果<$ c $只是什么都不做 c> TScalar 已经可以为空了。



基本上,我想要一个通用的通用类型,例如:




I find using _valueIsSet clumsy and would much prefer a Nullable<TScalar> where Nullable simply "does nothing" if TScalar is already nullable.

Basically, I want a generic generic type, e.g:

private MagicVoodooType<TScalar> _value;





其中:

1.当 TScalar 可以为例,例如字符串,然后 _value 将具有类型 TScalar

2.当 TScalar 不可为空,例如int,然后 _value 将具有类型 Nullable< TScalar>



我知道这是一个很长的镜头,但我之前已经讨论过这个,在另一个板上,一些评论者给我的印象是它可能有一些魔法,即IL级别的东西,但看到的是自从我第一次遇到这个要求以来,.NET框架已经取得了很大的进步,我想知道它现在是否更容易。



Where :
1. When TScalar is nullable, e.g. string, then _value will have type TScalar.
2. When TScalar is not nullable, e.g. int, then _value will have type Nullable<TScalar>.

I know this is a long shot, but I have been through discussions of this before, on another board, and some commenters gave me the impression it might be possible with some magic, i.e. IL level stuff, but seeing as the .NET framework has advanced a lot since my first encounter with this requirement, I was wondering if it might be easier now.

推荐答案

我不知道你是什么重做但看起来你需要确定 TScalar 是否可以为空?



也许你正在寻找这个:

I don't know what you're doing but it looks like you need to determine if TScalar is nullable?

Perhaps you're looking for this:
Type valueType = _value.GetType();

if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
    // Handle the case where TScalar is nullable...
}
else
{
    // Nope, not nullable.
}


这篇关于如何实现与Nullable&lt; T&gt;相同的方法。 T可以为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆