简体   繁体   English

优雅的方法来检查.Net对象是否为空

[英]Elegant way to check if .Net object is empty

I have an X509Certificate2 property, and I want to check in the set section, if the value that was set is empty. 我有一个X509Certificate2属性,如果要设置的值为空,我想检查一下set部分。 When I try to access to any X509Certificate2 property such as publickey, I got this exception: System.Security.Cryptography.CryptographicException occurred in mscorlib.dll . 当我尝试访问任何X509Certificate2属性(例如publickey)时,出现以下异常: mscorlib.dll发生了System.Security.Cryptography.CryptographicException

sure, I can write something such this example: 当然,我可以写一些这样的例子:

private static X509Certificate2 _certificate;

    public X509Certificate2 Certificate
    {
        get
        {
            return _certificate;
        }
        set
        {
            try
            {
                if (value.PublicKey != null)
                    _certificate = value;
            }
            catch(CryptographicException)
            {
                _certificate = null;
            }

        }
    } 

but I want a nicer way, does any one have an idea? 但是我想要一个更好的方法,有人有想法吗?

MSDN said "The key value is not an RSA or DSA key, or the key is unreadable." MSDN说:“密钥值不是RSA或DSA密钥,或者密钥不可读。” So maybe yours algorithm is not RSA or DSA. 因此,也许您的算法不是RSA或DSA。 Check what returns GetKeyAlgorithm() 检查返回什么GetKeyAlgorithm()

You can use the simple option - access the Handle property: 您可以使用简单的选项-访问Handle属性:

public X509Certificate2 Cretificate
{
   get { return _certificate; }
   set { _certificate = value.Handle == IntPtr.Zero ? null : value}
}

as I know, otherwise when you define: 据我所知,否则当您定义:

X509Certificate2 cert = new X509Certificate2();

and will try to set your certificate with the empty cert - you might get an exception. 并尝试使用空证书设置证书-您可能会遇到异常。

You can use the null coalescing operator : 您可以使用null合并运算符

public X509Certificate2 Certificate     
{
     get { return _certificate; }
     set { _certificate = value.PublicKey ?? null; }
}

Basically: 基本上:

_certificate = value.PublicKey is it isn't null, else it equals null. _certificate = value.PublicKey是否不为null,否则等于null。

But now writing this, I think that will not work, so might need to use a ternary : 但是现在写这篇文章,我认为那是行不通的,因此可能需要使用三进制

public X509Certificate2 Certificate     
{
     get { return _certificate; }
     set { _certificate = value == null ? null : value.PublicKey; }
}

Which means: 意思是:

_certificates = null if value is null, else it equals value.PublicKey _certificates = null,如果value为null,否则等于value.PublicKey

I think this is the right approach since your value being null will cause the Exception. 我认为这是正确的方法,因为您的值为null会导致异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM