关于覆盖与隐藏C#中的方法有点困惑.每个人的实际用途也将被理解,以及何时使用每个人的解释.
我对重写感到困惑 - 为什么要覆盖?到目前为止我所学到的是,通过覆盖,我们可以在不改变签名的情况下为派生类的方法提供所需的实现.
如果我不覆盖超类的方法并且我对子类中的方法进行了更改,那么是否会更改超类方法?
我也对以下内容感到困惑 - 这表明了什么?
class A
{
virtual m1()
{
console.writeline("Bye to all");
}
}
class B : A
{
override m1()
{
console.writeLine("Hi to all");
}
}
class C
{
A a = new A();
B b = new B();
a = b; (what is this)
a.m1(); // what this will print and why?
b = a; // what happens here?
}
Run Code Online (Sandbox Code Playgroud) 好的,这来自于此处的一些讨论.
想象一下以下场景.公司Alpha发布了库Charlie,其中暴露了一个显式Charlie.Bar实现接口的类型IFooable:
public interface IFooable
{
void Foo();
}
namespace Charlie
{
public clas Bar: IFooable
{
void IFooable.Foo() {...}
....
}
}
Run Code Online (Sandbox Code Playgroud)
现在它发生公司贝塔是继承Charlie.Bar在库Tango一些非常特殊的功能,其中明确落实IFooable.Foo不剪.Beta需要"覆盖"接口实现并实现看似等效的虚拟行为; 调用IFooable.Foo()应该正确解析对象的运行时类型.请注意,让公司Alpha修改实施Charlie.Bar不是一个可行的选择.
那么怎么做呢?显式接口方法在CIL中标记为virtual,final因此您不能覆盖它们.Beta提出了这个"黑客":
using Charlie;
namespace Tango
{
class Blah: Bar, IFooable
{
void IFooable.Foo() { //Bar specific implementation }
}
}
Run Code Online (Sandbox Code Playgroud)
请注意IFooable再次执行, …
我正在寻找一种简单的方法来获取从类开始的方法的反射信息,并一直返回到声明接口。下面是一段简化的代码:
public interface Ix
{
void Function();
}
public class X : Ix
{
public void Function() {}
}
public class Y : X
{
}
Run Code Online (Sandbox Code Playgroud)
类 X 的方法信息没有关于在 Ix 接口中声明的函数的信息。这是电话:
var info = typeof(X).GetMethod("Function");
var baseInfo = info.GetBaseDefinition()
Run Code Online (Sandbox Code Playgroud)
它返回以下数据:
info.DeclaringType --> MyNamespace.X
info.ReflectedType --> MyNamespace.X
baseInfo.DeclaringType --> MyNamespace.X
baseInfo.ReflectedType --> MyNamespace.X
Run Code Online (Sandbox Code Playgroud)
为类 Y 返回相同的信息。
我如何确定这个函数是在接口 Ix 中声明的,而无需遍历所有已实现的接口和类 X 或 Y 的基类?我可能会遗漏一些简单的东西,但我无法弄清楚是什么。这可能是一个错误吗?
这是 .Net Core SDK 版本 2.1.104 和 Visual Studio 2017