How can I use a parent class's member to satisfy an interface in C#?
I have the following situation:
public interface IStuffer
{
public string Foo { get; }
}
public class BaseClass
{
public static string Foo { get { ... } }
}
public class MyClass : BaseClass, IStuffer
{
}
This won't build because MyClass needs a Foo member. How can I use BaseClass's Foo implementation to satisfy MyClass's requirement for Foo?
It's because Foo is a static member of the BaseClass. Just take away the static keyword!
public class BaseClass
{
public string Foo { get { ... } }
}
Edit: Else if you really want it to stay static, you could use an explicit implementation
public class MyClass : BaseClass, IStuffer
{
string IStuffer.Foo { get { return BaseClass.Foo; } }
}
The problem is that your interface expects a NON-static "string Foo", if you make Foo Non-Static in BaseClass then it will satisfy your Interface :)
Good Luck
Interfaces cannot support static properties or methods. If you have an interface, all methods of that interface must be instance rather than class scope.
In two ways:
1. Rename Foo to something else and add a method Foo like this:
public class BaseClass
{
public static string FormerlyCalledFoo { get { ... } }
public string Foo { get { ... } }
}
2. If you absolutely must have a static Foo property then you can implement the IStuffer interface as an explicit interface implementation like this:
public class BaseClass : IStuffer
{
public static string Foo { get { ... } }
string IStuffer.Foo { get { ... } }
}
If using the latter method, then you have to be aware that you have to cast instances of BaseClass to IStuffer to access the IStuffer.Foo property
精彩评论