请问在 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>'
用 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);
}
}
C# 三个关键字operator搭配implicit和explicit即可实现。参照:博文https://www.cnblogs.com/xushitairan/p/10930750.html