Why I cannot define both implicit and explicit operators like so?
为什么我不能像这样定义隐式和显式运算符?
public class C
{
public static implicit operator string(C c)
{
return "implicit";
}
public static explicit operator string(C c)
{
return "explicit";
}
}
You can do this hack though :)
你可以这样做虽然:)
class Program
{
public class A
{
}
public class B
{
public static implicit operator A(B b)
{
Console.WriteLine("implicit");
return new A();
}
}
public class C : B
{
public static explicit operator A(C c)
{
Console.WriteLine("explicit");
return new A();
}
}
static void Main(string[] args)
{
C c = new C();
A a = c;
A b = (A) c;
}
}
This prints:
implicit
explicit
2 个解决方案
#1
Check this: Why can't coexist implicit and explicit operator of the same type in C#?
检查一下:为什么不能在C#*存相同类型的隐式和显式运算符?
If you define an explicit operator, you will be able to do something like this:
如果您定义一个显式运算符,您将能够执行以下操作:
Thing thing = (Thing)"value";
If you define an implicit operator, you can still do the above, but you can also take advantage of implicit conversion:
如果您定义了隐式运算符,您仍然可以执行上述操作,但您也可以利用隐式转换:
Thing thing = "value";
In short, explicit allows only explicit conversion, while implicit allows both explicit and implicit... hence the reason why you can only define one.
简而言之,explicit只允许显式转换,而implicit允许显式和隐式......因此你只能定义一个。
#2
I don't know the technical limitation that prevents this, but I think they would have done this to prevent people from shooting their own feet off.
我不知道阻止这种情况的技术限制,但我认为他们会这样做是为了防止人们自己开枪。
string imp = new C(); // = "implicit"
string exp = (string)new C(); // = "explicit"
That would drive me bonkers and makes no sense, C
should only cast to a string 1 way, not 2 different ways.
这会让我感到疯狂,没有任何意义,C只应该以一种方式投射到一个字符串,而不是两种不同的方式。
#1
Check this: Why can't coexist implicit and explicit operator of the same type in C#?
检查一下:为什么不能在C#*存相同类型的隐式和显式运算符?
If you define an explicit operator, you will be able to do something like this:
如果您定义一个显式运算符,您将能够执行以下操作:
Thing thing = (Thing)"value";
If you define an implicit operator, you can still do the above, but you can also take advantage of implicit conversion:
如果您定义了隐式运算符,您仍然可以执行上述操作,但您也可以利用隐式转换:
Thing thing = "value";
In short, explicit allows only explicit conversion, while implicit allows both explicit and implicit... hence the reason why you can only define one.
简而言之,explicit只允许显式转换,而implicit允许显式和隐式......因此你只能定义一个。
#2
I don't know the technical limitation that prevents this, but I think they would have done this to prevent people from shooting their own feet off.
我不知道阻止这种情况的技术限制,但我认为他们会这样做是为了防止人们自己开枪。
string imp = new C(); // = "implicit"
string exp = (string)new C(); // = "explicit"
That would drive me bonkers and makes no sense, C
should only cast to a string 1 way, not 2 different ways.
这会让我感到疯狂,没有任何意义,C只应该以一种方式投射到一个字符串,而不是两种不同的方式。