C# 如何调用';什么是显式接口实现?
基本问题(伪代码):C# 如何调用';什么是显式接口实现?,c#,explicit-interface,C#,Explicit Interface,基本问题(伪代码): 有没有办法在不从类A中删除显式实现的情况下实现此功能?我建议稍微更改基类,以便DoSomething调用受保护的方法: class A: ISomethingDoer { void ISomethingDoer.DoSomething() { DoSomethingImpl(); } protected void DoSomethingImpl() { Something.Do(); } } 然后在B中,您
有没有办法在不从类
A
中删除显式实现的情况下实现此功能?我建议稍微更改基类,以便DoSomething
调用受保护的方法:
class A: ISomethingDoer
{
void ISomethingDoer.DoSomething()
{
DoSomethingImpl();
}
protected void DoSomethingImpl()
{
Something.Do();
}
}
然后在B
中,您可以调用DoSomethingImpl
:
class B: A, ISomethingDoer
{
void ISomethingDoer.DoSomething()
{
if (reason)
{
DoSomethingImpl(); //this does compile
}
SomethingElse.Do();
}
}
建议的替代方法是使用反射:
class B: A, ISomethingDoer
{
void ISomethingDoer.DoSomething()
{
if (reason)
{
string baseName = $"{typeof(ISomethingDoer).FullName}.{nameof(DoSomething)}";
MethodInfo baseMethod = this.GetType().BaseType
.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
.FirstOrDefault(m => m.IsPrivate && m.IsFinal && m.Name == baseName);
baseMethod.Invoke(this, new object[0]);
}
SomethingElse.Do();
}
}
但我不喜欢这种方法,因为它使用反射,速度会慢一些。我曾经帮助我构建反射解决方案
如果需要过滤方法的不同重载,可以使用,并且可以通过构建一个以相同位置顺序包含参数的
对象[]
数组来指定参数。无法对接口类型调用base
,但可以重构类以实现这一点
通过将方法的内容移动到受保护的方法中,两个类都可以直接调用它,如下所示:
interface ISomethingDoer
{
void DoSomething();
}
class A : ISomethingDoer
{
void ISomethingDoer.DoSomething()
{
_DoSomething();
}
protected void _DoSomething()
{
Something.Do();
}
}
class B : A, ISomethingDoer
{
void ISomethingDoer.DoSomething()
{
if (reason)
{
base._DoSomething();
}
SomethingElse.Do();
}
}
这可能是一个很好的基本实现:
public interface IAnimal
{
void Eat();
}
public class Animal : IAnimal
{
public void Eat()
{
Console.WriteLine("This Animal is Eating!");
}
}
public class Shark : Animal
{
public void Eat(bool useBase)
{
if (useBase)
{
base.Eat();
}
else
{
Console.WriteLine("This Shark is devouring everything with 120840128904 teeth");
}
}
}
我总是将私有实现作为方法的包装
interface ISomethingDoer
{
void DoSomething();
}
class A : ISomethingDoer
{
protected void DoSomething()
{
Something.Do();
}
void ISomethingDoer.DoSomething() => DoSomething();
}
class B : A, ISomethingDoer
{
protected void DoSomethingElse()
{
if (reason)
{
base.DoSomething();
}
SomethingElse.Do();
}
void ISomethingDoer.DoSomething() => DoSomethingElse();
}
不是没有思考。引用这样一个问题:“有没有办法在不从类A中删除显式实现的情况下使它工作?”@John我删除了吗?是的,您删除了。显式接口实现看起来像
void IAnimal.Eat()
,而不是public void Eat()
。提供一个指示方法内部工作方式的参数对我来说似乎不太好。@HimBromBeere我也这么认为,我在他的示例中仅将其放在“reason”变量中,这可能是更糟糕的事情
interface ISomethingDoer
{
void DoSomething();
}
class A : ISomethingDoer
{
protected void DoSomething()
{
Something.Do();
}
void ISomethingDoer.DoSomething() => DoSomething();
}
class B : A, ISomethingDoer
{
protected void DoSomethingElse()
{
if (reason)
{
base.DoSomething();
}
SomethingElse.Do();
}
void ISomethingDoer.DoSomething() => DoSomethingElse();
}