首页 新闻 搜索 专区 学院

C# 隐式转换问题

0
悬赏园豆:50 [已解决问题] 解决于 2020-02-10 20:20

请问在 C# 中如何可以实现下面的式转换?

class Program
{
    static void Main(string[] args)
    {
        Versioned<AccessPermission> permission = AccessPermission.Anonymous;
    }
}

public enum AccessPermission
{
    Undefined = 0,
    Anonymous = 1
}

public struct Versioned<T>
{
    public T Value { get; }
    public int Version { get; }

    public Versioned(T value, int version)
    {
        Value = value;
        Version = version;
    }
}

上面的代码在编译时会报错:

Cannot implicitly convert type 'AccessPermission' to 'Versioned<ImplicitOperator.AccessPermission>'
C#
dudu的主页 dudu | 高人七级 | 园豆:38803
提问于:2020-02-10 18:38
< >
分享
最佳答案
0

用 implicit operator 可以搞定。

class Program
{
    static void Main(string[] args)
    {
        Versioned<AccessPermission> permission = 1;
        Console.WriteLine(permission.Value);
        permission = AccessPermission.Anonymous;
        Console.WriteLine(permission.Value);            
    }
}

public class LegacyBlogPost
{
    public AccessPermission Permission { get; set; }
}

public class BlogPost
{
    public Versioned<AccessPermission> Permission { get; set; }
}

public enum AccessPermission
{
    Undefined = 0,
    Anonymous = 1
}

public struct Versioned<T>
{
    public T Value { get; }
    public int Version { get; }

    public Versioned(T value, int version)
    {
        Value = value;
        Version = version;
    }

    public static implicit operator Versioned<T>(T permission)
    {
        return new Versioned<T>(permission, 1);
    }

    public static implicit operator Versioned<T>(int permission)
    {
        return new Versioned<T>((T)(object)permission, 1);
    }
}
dudu | 高人七级 |园豆:38803 | 2020-02-10 20:16
其他回答(1)
0

C# 三个关键字operator搭配implicit和explicit即可实现。参照:博文https://www.cnblogs.com/xushitairan/p/10930750.html

VueDi | 园豆:206 (菜鸟二级) | 2020-02-11 22:15
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册