隐式转换为子类还不够吗?
Implicit conversion to subclass not sufficient?
我正在使用一个库,该库具有由特定类型的对象表示的语言 Language
,而在我的代码中,我使用的是另一个库中的枚举 LanguageEnum
,但我不能改变。无论如何,我正在尝试构建从枚举到 Lanuage
class 的隐式转换。
我的想法:创建 Lanuage
的子 class —— 比方说 SubLanguage
并添加从语言枚举到此 class 的隐式转换。
虽然我可以做到,但并不能解决我的问题。当我在需要 Language
的地方使用我的 LanugageEnum
时,编译器抱怨没有转换,尽管编译器可以转换为实际上应该足够的 SubLanguage
。
代码如下所示:
public void DoSomethingWith(Language lang) {
}
// somewhere else I call it like this
DoSomethingWith(LanguageEnum.German);
是否可以在不使用显式转换的情况下解决我的问题?
如果你想要隐式转换,你需要在目标类型中准确指定它,而不是它的子类型——否则编译器根本不会考虑它。
请参阅 C# 规范的相关部分,6.4.4 用户定义的隐式转换:
A user-defined implicit conversion from type S to type T is processed as follows:
Determine the types S0 and T0. If S or T are nullable types, S0 and T0 are their underlying types, otherwise S0 and T0 are equal to S and T respectively.
Find the set of types, D, from which user-defined conversion operators will be considered. This set consists of S0 (if S0 is a class or struct), the base classes of S0 (if S0 is a class), and T0 (if T0 is a class or struct).
因此,如果您要分配给 Language
类型的变量或字段或参数,则需要在此处声明转换,而不是在 SubLanguage
.
中
但是,如果我可以这样说的话,请不要只关注隐式转换。在长运行中,使操作明确可见并没有错。特别是如果它们是巨大的表示更改操作。
我正在使用一个库,该库具有由特定类型的对象表示的语言 Language
,而在我的代码中,我使用的是另一个库中的枚举 LanguageEnum
,但我不能改变。无论如何,我正在尝试构建从枚举到 Lanuage
class 的隐式转换。
我的想法:创建 Lanuage
的子 class —— 比方说 SubLanguage
并添加从语言枚举到此 class 的隐式转换。
虽然我可以做到,但并不能解决我的问题。当我在需要 Language
的地方使用我的 LanugageEnum
时,编译器抱怨没有转换,尽管编译器可以转换为实际上应该足够的 SubLanguage
。
代码如下所示:
public void DoSomethingWith(Language lang) {
}
// somewhere else I call it like this
DoSomethingWith(LanguageEnum.German);
是否可以在不使用显式转换的情况下解决我的问题?
如果你想要隐式转换,你需要在目标类型中准确指定它,而不是它的子类型——否则编译器根本不会考虑它。
请参阅 C# 规范的相关部分,6.4.4 用户定义的隐式转换:
A user-defined implicit conversion from type S to type T is processed as follows:
Determine the types S0 and T0. If S or T are nullable types, S0 and T0 are their underlying types, otherwise S0 and T0 are equal to S and T respectively.
Find the set of types, D, from which user-defined conversion operators will be considered. This set consists of S0 (if S0 is a class or struct), the base classes of S0 (if S0 is a class), and T0 (if T0 is a class or struct).
因此,如果您要分配给 Language
类型的变量或字段或参数,则需要在此处声明转换,而不是在 SubLanguage
.
但是,如果我可以这样说的话,请不要只关注隐式转换。在长运行中,使操作明确可见并没有错。特别是如果它们是巨大的表示更改操作。