C# 接口不能包含运算符 [英] C# interface cannot contain operators

查看:36
本文介绍了C# 接口不能包含运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下为什么 C# 接口不允许包含运算符?

Can anyone please explain why C# interfaces are not allowed to contain operators?

谢谢.

推荐答案

C# 运算符必须是静态的.根据定义,接口适用于实例.没有机制要求类型来实现静态成员.

C# operators have to be static. Interfaces, by definition, apply to instances. There is no mechanism to require a type to implement static members.


从 C# 8.0 开始,如您所见 此处,现在可以在接口中定义本地方法并在接口本身内实现它们,例如允许创建方法重载而不需要实现关心这些重载,当它们可能只是为必须实现的重载提供一个额外的参数时.
除此之外,您还可以在接口中定义运算符,但它们必须是静态的,因此必须在接口中实现.


Since C# 8.0, as you can see here, it is now possible to define local methods in interfaces and implement them within the interface itself, e.g. allowing to create method overloads without requiring implementations to care about those overloads as well, when they might just supply an additional parameter to the overload that has to be implemented.
Along with this, you can also define operators within interfaces, though they must be static and so they must be implemented in the interface.

因此,在 C# 8.0 中,这将打印this works in C# 8"后跟1":

So in C# 8.0 this will print "this works in C# 8" followed by "1":

interface ICanAdd
{
    int Value { get; }

    public static int operator+ (ICanAdd lvalue, int rvalue)
    {
        Console.WriteLine("this works in C# 8");
        return lvalue.Value + rvalue;
    }
}

class Add : ICanAdd
{
    public int Value => 0;
}

class Program
{
    static void Main(string[] args)
    {
        ICanAdd foo = new Add();
        var x = foo + 1;
        Console.WriteLine(x);
    }
}

编辑 2020-01-23

不能在接口中添加转换、相等或不等运算符,否则会出现以下错误:

You cannot add conversion, equality or inequality operators to interfaces, otherwise you'll hit the following error:

CS0567 C# 接口不能包含转换、相等或不等运算符

CS0567 C# Interfaces cannot contain conversion, equality, or inequality operators

这篇关于C# 接口不能包含运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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