将“set”添加到 C# 中的接口属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/623824/
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
Add 'set' to properties of interface in C#
提问by strager
I am looking to 'extending' an interface by providing set accessors to properties in that interface. The interface looks something like this:
我希望通过为该接口中的属性提供 set 访问器来“扩展”接口。界面看起来像这样:
interface IUser
{
string UserName
{
get;
}
}
I want something like this:
我想要这样的东西:
interface IMutableUser : IUser
{
string UserName
{
get;
set;
}
}
I need the inheritence. I cannot copy the body of IUser
into IMutableUser
and add the set accessors.
我需要继承。我无法复制IUser
into的主体IMutableUser
并添加 set 访问器。
Is this possible in C#? If so, how can it be accomplished?
这在 C# 中可能吗?如果是这样,如何实现?
采纳答案by Chris Shaffer
I don't see any reason why what you have posted shouldn't work? Just did a quick test and it compiles alright, but gives a warning about hiding. This can be fixed by adding the new keyword, like this:
我看不出有什么理由为什么您发布的内容不起作用?刚刚做了一个快速测试,它编译没问题,但给出了关于隐藏的警告。这可以通过添加 new 关键字来解决,如下所示:
public interface IMutableUser : IUser
{
new string Username { get; set; }
}
An alternative would be to add explicit set methods; eg:
另一种方法是添加显式 set 方法;例如:
public interface IMutableUser : IUser
{
void SetUsername(string value);
}
Of course, I'd prefer to use setters, but if it's not possible, I guess you do what you have to.
当然,我更喜欢使用 setter,但如果不可能,我想你会做你必须做的。
回答by Darin Dimitrov
You could use an abstract class:
您可以使用抽象类:
interface IUser
{
string UserName
{
get;
}
}
abstract class MutableUser : IUser
{
public virtual string UserName
{
get;
set;
}
}
Another possibility is to have this:
另一种可能性是有这个:
interface IUser
{
string UserName
{
get;
}
}
interface IMutableUser
{
string UserName
{
get;
set;
}
}
class User : IUser, IMutableUser
{
public string UserName { get; set; }
}
回答by womp
You can "override" properties in an interface by explicitly implementing the interfaces. Chris' answer is likely all you'll need for the scenario you've outlined, but consider a slightly more complex scenario, where you need a getter/setter on your class, but the interface only defines the getter. You can get around this by doing the following:
您可以通过显式实现接口来“覆盖”接口中的属性。Chris 的回答可能是您概述的场景所需的全部内容,但请考虑一个稍微复杂的场景,您的类需要一个 getter/setter,但接口只定义了 getter。您可以通过执行以下操作来解决此问题:
public class MyUser : IUser
{
IUser.MyProperty { get { return "something"; } }
public MyProperty { get; set; }
}
By explicitly implementing IUser.MyProperty
, you satisfy the contract. However, by providing public MyProperty
, the API for your object will never show the explicit interface version, and will always use MyProperty with the get/set.
通过显式实现IUser.MyProperty
,您就满足了契约。但是,通过提供 public MyProperty
,您对象的 API 将永远不会显示显式接口版本,并且将始终将 MyProperty 与 get/set 一起使用。