简体   繁体   English

C#泛型隐式运算符返回类型

[英]C# generic implicit operator return type

For purposes of automatically translating code from C++ to C#, I would like to have a C# class (psuedo-code) 为了自动将代码从C ++转换为C#,我希望有一个C#类(伪代码)

class Null {
    public static implicit operator T (Null unused) {
        return null;
    }
}

This would be useful in cases such as 这在诸如此类的情况下非常有用

foo(T1 x) { ... }
foo(T2 x) { ... }

foo(null); // ambiguous

For certain reasons, programmatically disambiguating the above type is not in general possible. 出于某些原因,通常不可能以编程方式消除上述类型的歧义。 Eg 例如

foo((T1)null); // Discovering T1 over T2 is not possible or really hard to do

But if I had the Null class above, I could programmatically add in 但如果我有上面的Null类,我可以通过编程方式添加

foo(Null x) {...}

and generate 并生成

foo(new Null()); // not ambiguous

The trick would be to use new Null() in place of every generated null such that even 诀窍是使用new Null()代替每个生成的null ,即使是偶数

T1 x = new Null();

compiles with x == null . x == null编译。

Is it possible to write such a class? 是否可以写这样的课程?

No. Absent the dynamic keyword, all method binding in C# is done at compile-time--even binding to implicit cast operators. 没有dynamic关键字,C#中的所有方法绑定都是在编译时完成的 - 甚至绑定到隐式转换运算符。 That means that the problem you're running into with method overload resolution will also prevent the compiler from being able to figure out whether you want your null to be implicitly cast to a T1 or a T2. 这意味着您遇到的方法重载解决问题也会阻止编译器确定是否要将null隐式强制转换为T1或T2。 And using dynamic won't work, because null doesn't have any type at runtime. 并且使用dynamic将无法工作,因为null在运行时没有任何类型。

It is possible that there are other solutions to your problem if you can share more information. 如果您可以共享更多信息,则可能存在其他问题的解决方案。 For example, if either of the two methods would work correctly when passed a null value, and you're just trying to get the generated code to compile, you could create a method like this: 例如,如果两个方法中的任何一个在传递空值时都能正常工作,并且您只是想尝试生成生成的代码,那么您可以创建一个这样的方法:

foo(object o) {return Foo((T1)null);}

And then translate calls to: 然后将调用转换为:

foo(new object());

The above method would also work if you wanted to use a Null class instead of object --no implicit cast is necessary. 如果你想使用Null类而不是object ,上面的方法也可以工作 - 不需要隐式强制转换。

On the other hand, if it does matter which overload gets called with a null value, then you need to tell us how the original program determines which one to call. 另一方面,如果使用空值调用哪个重载确实很重要,那么您需要告诉我们原始程序如何确定调用哪个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM