C#泛型类的运营商不工作 [英] C# generics class operators not working

查看:160
本文介绍了C#泛型类的运营商不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用的问题。当我尝试在普通使用更少的运营商,他们的呼叫没有发生。但是,它的工作原理与方法Equals。
这是一些测试类:

 公共类测试
{
公众诠释我;

静态公布尔运算符==(测试OBJ1,测试OBJ2)
{
Console.WriteLine(==操作符);
返回obj1.i == obj2.i;
}

静态公布尔运算符=(测试OBJ1,测试OBJ2)
{
Console.WriteLine(操作符=!)!;
返回obj1.i = obj2.i!;
}

公众覆盖布尔等于(obj对象)
{
Console.WriteLine(经营者等于);
返回此==(测试)目标文件;
}

公共覆盖INT的GetHashCode()
{
Console.WriteLine(的hashCode);
返回5;
}
}

和类检查:

 公共类检查
{
公布尔TestGeneric< T>(T左,T右)其中T:类
{
返回左==权利; //不行覆盖运营商
返回Left.Equals(右); //做工精细
}
}



小测试:



 测试左=新的测试(){I = 4}; 
测试右=新的测试(){I = 4};
VAR检查=新检查();
Console.WriteLine(checker.TestGeneric<试验>(左,右));
Console.ReadKey();



我如何使用类测试较少运营商从通用的?


< DIV CLASS =h2_lin>解决方案

重载操作符是静态方法,所以他们不参加多态性;他们是在编译时静态解析的基础上,已知类型的操作数。



在泛型方法,编译器无法知道 ŧ测试(因为它实际上可能是别的),所以它使用的最普遍的定义== ,这是参考比较。



请注意,如果你在泛型方法添加约束,迫使 T 测试测试的子类,它会如预期,但当然它不会为其他类型的工作了......


I have a problem with generic. When I try to use less operators in generic, their call is not happening. But it works with the method Equals. That is a some test 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:

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?

解决方案

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.

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...

这篇关于C#泛型类的运营商不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆