我在C#中定义了从/到某种类型的隐式字符串转换(虚拟代码):
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;
}
}
在外部库代码的某处,一个 MyType
的实例被作为 object
参数传递给一个方法。该方法的部分代码看起来类似于以下内容:
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
}
}
为什么演员没有使用隐式转换器?我认为这些的整点是使转换和透明使用变得可能?
如果 MyType
有一个 explicit
转换器,这是否有效?如果是这样,我怎样才能同时拥有两个?
顺便说一下,如果类型在编译时已知,则转换确实有效。这是因为操作符是static
吗?是否存在非静态转换操作符?
P.S. 实际上,我最感兴趣的是编译时行为和运行时行为之间的差异,因此我有一个后续问题:为什么 C# 中的隐式类型转换操作符不能在运行时动态使用?
as
运算符被称为“软转换”。 - Jon Skeet