Imagine an interface hierarchy like this:
public interface IAnimal
{
string Color { get; }
}
public interface ICat : IAnimal
{
}
In this case, ICat 'inherits' IAnimal's Color property.
Is it possible to add an attribute to the ICat's Color property, withou开发者_运维知识库t adding it to the IAnimal?
The following is an example of what I am trying to achieve, but gives a compiler warning:
public interface IAnimal
{
string Color { get; }
}
public interface ICat : IAnimal
{
[MyProperty]
string Color { get; }
}
This compiles for me in C# 4.0 beta 2. It does give a warning that the 'new' keyword might be warranted.
Also for the curious, this struck me as interesting: http://blogs.msdn.com/ericlippert/archive/2009/09/14/what-s-the-difference-between-a-partial-method-and-a-partial-class.aspx
I assume the warning you are getting is
warning CS0108: 'ICat.Color' hides inherited member 'IAnimal.Color'. Use the new keyword if hiding was intended.
What are you trying to accomplish by applying that attribute?
If you want to avoid that warning you might do something like the following:
public class MyPropertyAttribute : Attribute { }
public interface IAnimal {
string Color { get; }
}
public abstract class Cat : IAnimal {
[MyProperty]
public string Color {
get { return CatColor; }
}
protected abstract string CatColor {
get;
}
}
精彩评论