简体   繁体   English

C# generics class 操作员不工作

[英]C# generics class operators not working

I have a problem with generic.我对泛型有疑问。 When I try to use less operators in generic, their call is not happening.当我尝试在泛型中使用 less 运算符时,他们的调用没有发生。 But it works with the method Equals.但它适用于 Equals 方法。 That is a some test class:那是一些测试 class:

public class Test
{
    public int i;

    static public Boolean operator ==(Test obj1, Test obj2)
    {
        Console.WriteLine("operator ==");
        return obj1.i == obj2.i;
    }

    static public Boolean operator !=(Test obj1, Test obj2)
    {
        Console.WriteLine("operator !=");
        return obj1.i != obj2.i;
    }

    public override bool Equals(object obj)
    {
        Console.WriteLine("operator equals");
        return this == (Test)obj;
    }

    public override int GetHashCode()
    {
        Console.WriteLine("HashCode");
        return 5;
    }
}

And class Checker:和 class 检查员:

public class Checker
{
    public Boolean TestGeneric<T>(T Left, T Right) where T : class
    {
        return Left == Right; //not work override operators
        return Left.Equals(Right); //work fine
    }
}

Small testing:小测试:

Test left = new Test() { i = 4 };
Test right = new Test() { i = 4 };
var checker = new Checker();
Console.WriteLine(checker.TestGeneric<Test>(left, right));
Console.ReadKey();

How I can use less operators in class Test from generic?我如何在 class 通用测试中使用较少的运算符?

Overloaded operators are static methods, so they don't participate in polymorphism; 重载运算符是静态方法,因此它们不参与多态; they are resolved statically at compile time, based on the known type of the operands. 它们在编译时基于已知的操作数类型进行静态解析。

In a generic method, the compiler can't know that T will be Test (since it could actually be anything else), so it uses the most general definition of == , which is reference comparison. 在通用方法中,编译器不能知道T将是Test (因为它实际上可能是其他任何东西),因此它使用==的最一般定义,即参考比较。

Note that if you add a constraint on the generic method to force T to be Test or a subclass of Test , it will work as expected, but of course it won't work anymore for other types... 请注意,如果您对泛型方法添加约束迫使TTest或子类Test ,它会达到预期效果,但当然不会对其他类型的工作了......

This now works in C# 11 / .NET 7 (or above):这现在适用于 C# 11 / .NET 7(或以上):

public class Test : IEqualityOperators<Test, Test, bool>
{ /* no changes except ^^^ addition */ }

public bool TestGeneric<T>(T Left, T Right) where T : IEqualityOperators<T, T, bool>
{
    return Left == Right; // does what you expect
}

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

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