你可以使用C#new关键字在接口上扩展属性? [英] Can you use the C# new keyword to expand properties on an interface?

查看:245
本文介绍了你可以使用C#new关键字在接口上扩展属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解的新的关键字如何隐藏在派生类中的方法。但是,它有实现使用关键字接口的类有什么影响?

I understand how the "new" keyword can hide methods in a derived class. However, what implications does it have for classes that implement interfaces that use the keyword?

考虑这个例子,在这里我决定通过其属性读/写扩展接口

Consider this example, where I decide to expand an interface by making its properties read/write.

public interface IReadOnly {

   string Id {
      get;
   }
}

public interface ICanReadAndWrite : IReadOnly  {

   new string Id {
      get;
      set;
   }
}



然后你可以做这样的事情:

Then you are able to do things like this:

public IReadOnly SomeMethod() {
   // return an instance of ICanReadAndWrite
}

这是不好的设计?它会导致一些问题我班实现ICanReadAndWrite

Is this bad design? Will it cause issues for my classes that implement ICanReadAndWrite?

编辑:下面是一个人为的例子的为什么的我可能想要做这样的事情:

Here is a contrived example of why I might want to do something like this:

说我有一个工厂类返回一个IShoppingCartItemReadWrite。然后我可以有操纵它的价格,改变的东西一个服务层,等等。然后,我可以通过这些对象作为IShoppingCartItemReadOnly某种表现层不会改变他们。 (是的,我知道它在技术上的可以的变化them--这是一个设计问题,而不是安全,等等。)

Say I have a factory class that returns an IShoppingCartItemReadWrite. I can then have a service layer that manipulates prices on it, changes stuff, etc. Then, I can pass these objects as IShoppingCartItemReadOnly to some kind of presentation layer that won't change them. (Yes, I know it technically can change them-- this is a design question, not security, etc.)

推荐答案

这不是一个特别坏主意。你应该知道该实现的可以(如果它含蓄地实现了接口,那么一个读/写属性能同时满足接口)提供了两种不同的实现方式:

It's not a particularly bad idea. You should be aware that the implementor can (if it implicitly implements the interface, then a single read/write property could satisfy both interfaces) provide two distinct implementations:

class Test : ICanReadAndWrite {
   public string Id {
      get { return "100"; }
      set { }
   }
   string IReadOnly.Id {
      get { return "10"; }
   }
}

Test t = new Test();
Console.WriteLine(t.Id);  // prints 100
Console.WriteLine(((IReadOnly)t).Id); // prints 10



顺便说一句,在一般情况下,继承修改什么都不做,除了告诉编译器闭嘴,别扔了一个你隐藏该成员的警告。省略它将在编译的代码没有任何影响。

By the way, in general, the new inheritance modifier does nothing except to tell the compiler to shut up and don't throw out a "you're hiding that member" warning. Omitting it will have no effect in the compiled code.

这篇关于你可以使用C#new关键字在接口上扩展属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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