我们可以在 C#.NET 的接口中添加变量和属性吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1944432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:05:17  来源:igfitidea点击:

Can we add variables and properties in interfaces in C#.NET?

c#

提问by Kiran Thokal

I want to know that how to add variables (i.e. with which access specifier) in interfaces and also can we write property in interfaces in C#.net?

我想知道如何在接口中添加变量(即使用哪个访问说明符)以及我们是否可以在 C#.net 的接口中编写属性?

采纳答案by Gishu

This should have been easy to find on the internet.

这应该很容易在互联网上找到。

Interfaces are contracts to be fulfilled by implementing classes. Hence they can consist of publicmethods, properties and events (indexers are permitted too).

接口是通过实现类来实现的契约。因此它们可以由公共方法、属性和事件组成(也允许索引器)。

Variables in Interfaces - NO. Can you elaborate on why you need them? You can have variables in Base classes though.
Properties in Interfaces - Yes, since they are paired methods under the hood.
Members of an interface are implicitly public. You cannot specify access modifiers explicitly

接口中的变量 - 否。你能详细说明你为什么需要它们吗?不过,您可以在基类中使用变量。
接口中的属性 - 是的,因为它们在幕后是成对的方法。
接口的成员是隐式公开的。您不能显式指定访问修饰符

public interface ISampleInterface
{
    // method declaration
    bool CheckSomething(object o);

    // event declaration
    event EventHandler ShapeChanged;

    // Property declaration:
    string Name
    {
        get;
        set;
    }
}

See also

也可以看看

回答by o.k.w

Variables in interfaces, I don't think so but I'm not 100% certain?

接口中的变量,我不这么认为,但我不是 100% 确定?

And yes, you can have properties in interfaces. See the MSDN reference:
Interface Properties (C# Programming Guide)

是的,您可以在接口中拥有属性。请参阅 MSDN 参考:
接口属性(C# 编程指南)