简体   繁体   English

C# 如何允许接口具有带有 getter/setter 的成员变量?

[英]How can C# allow interface's to have member variables with getters/setters?

-For as long as I can remember, I always thought that interfaces in Java and C# would only allow the following in an interface --constants --method signatures -从我记事起,我一直认为 Java 和 C# 中的接口只允许接口中的以下内容 --constants --method 签名

1) How can C# allow interface's to have member variables with getters/setters? 1) C# 如何允许接口拥有带有 getter/setter 的成员变量?

public interface IEntityBase
{
    ObjectId _id { get; set; }
}

2) Would Java allow for something similar to the aforementioned C# code? 2) Java 是否允许类似于上述 C# 代码的内容?

A property is not a member variable.属性不是成员变量。 Think of it as a replacement for the old technique of a private variable with GetVarA() and SetVarA(int varA) methods exposing it.将其视为使用 GetVarA() 和 SetVarA(int varA) 方法公开私有变量的旧技术的替代。

All a property really is, is that with neater syntax.真正的属性就是具有更简洁的语法。 That's why it can exist in an interface, as technically it's not defining a variable at all - your implementation of string MyName {get;} could have a private 'myName' member variable backing it up, whereas someone elses could grab the name from a database each time the property's Get was called.这就是为什么它可以存在于接口中的原因,因为从技术上讲它根本没有定义变量 - 您对字符串 MyName {get;} 的实现可以有一个私有的“myName”成员变量来支持它,而其他人可以从每次调用该属性的 Get 时都会调用数据库。

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

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