加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么访问枚举定义中不存在的枚举成员(通过转换整数)不会

发布时间:2020-12-15 08:17:54 所属栏目:百科 来源:网络整理
导读:要修复我的应用程序中的错误,我必须设置System.Net程序集中找到的ServicePointManager类的SecurityProtocolType,如下所示: ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; 在.Net 4.5中,SecurityProtocolType枚举有四个成员: public
要修复我的应用程序中的错误,我必须设置System.Net程序集中找到的ServicePointManager类的SecurityProtocolType,如下所示:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

在.Net 4.5中,SecurityProtocolType枚举有四个成员:

public enum SecurityProtocolType
{
    Ssl3 48,Tls 192,Tls11 768,Tls12 3072
}

但是,在.Net 4.0中,SecurityProtocolType枚举只有两个成员:

public enum SecurityProtocolType
{
    Ssl3 48,Tls 192
}

因为,我的代码中的另一个项目也需要相同的修复,但该项目是在.Net 4.0上没有Tls12作为枚举的成员,this答案提出了以下解决方法(前提是我安装了.Net 4.5)框):

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

可能是我遗漏了明显的smoething,但我的问题是,当3072不是.Net 4.0中枚举的有效值时,(SecurityProtocolType)3072如何解析为Tls12.我想了解幕后工作的魔力是什么.

解决方法

从C#中的枚举文档( MSDN)

A variable of type Day can be assigned any value in the range of the underlying type; the values are not limited to the named constants.

因此代码肯定没有问题编译.此外:

Just as with any constant,all references to the individual values of an enum are converted to numeric literals at compile time. This can create potential versioning issues as described in Constants.

Assigning additional values to new versions of enums,or changing the values of the enum members in a new version,can cause problems for dependent source code.

你实际上正在利用这一点.在.NET 4.0上运行时,框架不知道如何处理3072值,但.NET 4.5框架可以.您只是没有方便的快捷方式(枚举)来获取该值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读