不,你不能这样做。 C# 规范很明确,您的 implicit 运算符 必须 转换为或从其声明的类型转换。它必须是精确 转换,并且由于声明类型正好是MyClass<T>,因此转换必须是到那个或来自那个。
参见例如Can i use a generic implicit or explicit operator? C# 和 C# Implicit operator with generic。
冒着宽恕或认可XY Problem 的风险,这里有几个骇人听闻的替代方案:
// Break generics by checking the type explicitly. Requires ugly casting
// and intermediate boxing, though it's possible that with some run-time
// use of Expressions, you could cache a delegate that would handle the
// conversion without the boxing. It'd still be ugly though.
class Class1<T>
{
public Class1(T t) { }
public static implicit operator Class1<T>(bool value)
{
if (typeof(T) == typeof(string))
{
return (Class1<T>)(object)(Class1OfString)value;
}
throw new InvalidOperationException("Invalid type T");
}
}
// Subclass the generic, and declare the conversion there. Of course, then
// to use the conversion, you have to reference this type explicitly. Ugly.
class Class1OfString : Class1<string>
{
public Class1OfString(string text) : base(text) { }
public static implicit operator Class1OfString(bool value)
{
return new Class1OfString(value.ToString());
}
}
class A
{
public static void M()
{
// These all compile and execute fine
Class1OfString c1 = true;
Class1<string> c2 = (Class1OfString)true;
Class1<string> c3 = true;
}
}
上面的主题有许多变体,但它们都将涉及以某种方式规避和特殊封装类型。
值得指出的是,除了这里处理泛型与特定的困难外,implicit 的使用还有其他原因值得怀疑。 The documentation 在顶部声明应该只使用implicit “如果保证转换不会导致数据丢失” 并且实现“不应该抛出异常”时间>。在这两种情况下,这是“以便在程序员不知情的情况下可以安全地使用它们”。换句话说,implicit 的本质是它们被隐式调用,程序员甚至不需要考虑它。所以它们必须总是工作,而上面的一些例子不一定是这种情况(在一个例子中,无论如何你必须使用显式语法,所以你不妨实现运算符还是explicit)。
这些选项都不理想。但坦率地说,原来的情况也不是。泛型类型必须在特定的基础上处理具体类型是很奇怪的。它首先质疑泛型类型是否真的应该是泛型的。您可能真的应该做一些更像上面的子类化示例的事情,只是进一步应用。 IE。将泛型类型用于您需要的任何基本行为,但将所有特化放入您知道类型参数 T 的子类中。
鉴于问题中缺乏细节,我无法提供更多建议。但基本要求不够可靠,足以表明,如果问题包含更广泛的问题陈述和详细说明导致您实现此实际实施目标的原因,可能会提供更好、更适用的答案。