zoukankan      html  css  js  c++  java
  • 【转】C#中的implicit 和 explicit

    The implicit and explicit keywords in C# are used when declaring conversion operators. Let's say that you have the following class:

    public class Role
    {
        public string Name { get; set; }
    }
    

    If you want to create a new Role and assign a Name to it, you will typically do it like this:

    Role role = new Role();
    role.Name = "RoleName";
    

    Since it has only one property, it would perhaps be convenient if we could instead do it like this:

    Role role = "RoleName";
    

    This means that we want to implicitly convert a string to a Role (since there is no specific cast involved in the code). To achieve this, we add an implicit conversion operator:

    public static implicit operator Role(string roleName)
    {
        return new Role() { Name = roleName };
    }
    

    Another option is to implement an explicit conversion operator:

    public static explicit operator Role(string roleName)
    {
        return new Role() { Name = roleName };
    }
    

    In this case, we cannot implicitly convert a string to a Role, but we need to cast it in our code:

    Role r = (Role)"RoleName";
  • 相关阅读:
    将博客搬至CSDN
    HDU1175 + HDU1728+BFS转弯
    HDU1401 BFS
    HDU1401 双广BFS
    分布式一致性
    GFS架构分析
    云计算资源分享与下载
    mysql导入导出数据方法
    缓存设计的一些思考
    HBase性能优化方法总结
  • 原文地址:https://www.cnblogs.com/mimime/p/5821247.html
Copyright © 2011-2022 走看看