为什么在" AS"经营者不得使用在C#中的隐式转换操作符? [英] Why does the "as" operator not use an implicit conversion operator in C#?
问题描述
我已经定义了隐式串转换自/至某一类在C#(虚拟代码):
公共类的MyType
{
公共字符串值{获得;组; }
公共静态隐运营商的MyType(字符串fromString)
{
返回新的MyType {值= fromString};
}
公共静态隐运营商的字符串(的MyType的myType)
{
返回myType.Value;
}
}
某处在外部库代码的实例的MyType
被传递给方法,为对象
参数。该方法的部分看起来像沿着这些路线的内容:
私人无效美孚(对象的值)
{
// ...省略代码
无功吧=值作为字符串//注意,值是在运行时
如果(巴!= NULL)的MyType的实例//假的,转换失败
{
// ...代码中省略
}
}
为什么投不使用隐式转换器?我想到这些整点是使铸造和透明的使用可能吗?
这会工作,如果的MyType
过一个明确
转换呢?如果是这样,我(怎么)可以兼得?
顺便说一句,如果该类型是在已知的演员肯定工程的编译时间 。这是因为运营商静态
?有什么样的非静态转换操作?
P.S。实际上,我最感兴趣的是编译时行为和运行时行为之间的差异,所以我有一个跟进的问题:为什么隐式类型转换操作符在C#中运行时不能动态使用吗?
为什么软投不使用隐式转换器?
块引用>
好吧,这就是语言指定,基本的方式。从C#5规范的第11年7月10日:
如果E的编译时类型不是动态的,操作ê为T产生相同的结果。
电子为T? (T)(E):(T)空
除了E被只计算一次。
...]
请注意,某些转换,如用户定义的转换,是不可能的as运算符,而应使用强制转换表达式来执行。
块引用>I have defined implicit string conversion from/to a certain type in C# (dummy code):
public class MyType { public string Value { get; set; } public static implicit operator MyType(string fromString) { return new MyType { Value = fromString }; } public static implicit operator string(MyType myType) { return myType.Value; } }
Somewhere in external library code, an instance of
MyType
is passed to a method, as anobject
parameter. Part of that method looks like something along these lines:private void Foo(object value) { // ... code omitted var bar = value as string // note that value is an instance of MyType at runtime if(bar != null) // false, cast fails { // ... code omitted } }
Why does the cast not use the implicit converter? I thought the whole point of these was to make casting and transparent usage possible?
Would this work if
MyType
had anexplicit
converter instead? If so, (how) can I have both?By the way, the cast definitely works if the type is known at compile-time. Is this because operators are
static
? Is there something like non-static conversion operators?P.S. I'm actually most interested in the differences between compile-time behaviour and runtime behaviour, so I've a follow-up question: Why are implicit type conversion operators not dynamically usable at runtime in C#?
解决方案Why does the soft cast not use the implicit converter?
Well, that's the way the language is specified, basically. From the C# 5 specification section 7.10.11:
If the compile-time type of E is not dynamic, the operation E as T produces the same result as
E is T ? (T)(E) : (T)null
except that E is only evaluated once.
[...]
Note that some conversions, such as user defined conversions, are not possible with the as operator and should instead be performed using cast expressions.
这篇关于为什么在" AS"经营者不得使用在C#中的隐式转换操作符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!