Tag: virtual method

如何检测是否在c#中重写了虚方法

是否可以确定是否已覆盖虚拟方法: class ABase { public void DoSomething(object p) { p.Process(); if( /* DoSomethingExtra is implemented */ ) DoSomethingExtra(p); } public virtual void DoSomethingExtra(object p) { } } class ADerived { public override void DoSomethingExtra(object p) { p.ProcessMore(); } } 我意识到这个例子看起来很愚蠢(例如,你为什么不调用DoSomethingExtra(),因为它没有做任何事情)。 我向你保证,我有一个合法的案例。 有任何想法吗?

使用reflection覆盖C#中的虚方法表

有没有办法在C#中更改虚方法表? 喜欢改变虚拟方法指向的位置? class A { public virtual void B() { Console.WriteLine(“B”); } } class Program { public static void MyB(A a) { Console.WriteLine(“MyB”); } public static void Main(string[] Args) { A a = new A(); // Do some reflection voodoo to change the virtual methods table here to make B point to MyB aB(); // […]

覆盖函数c#

我只是试图使用控制台应用程序来掌握虚拟function的概念。 我注意到,一旦覆盖基类函数, 返回baseclassname.functionname(parameters)就会自动插入到我的函数体中。 为什么会这样? class advanc { public virtual int calc (int a , int b) { return (a * b); } } class advn : advanc { public override int calc(int a, int b) { //automatically inserted return base.calc(a, b); } }

Expression.Compile与Lambda的性能,直接与虚拟调用

我很好奇Expression.Compile与代码中的lambda表达式和直接方法使用方式的性能如何,以及直接方法调用与虚方法调用(伪代码): var foo = new Foo(); var iFoo = (IFoo)foo; foo.Bar(); iFoo.Bar(); (() => foo.Bar())(); (() => iFoo.Bar())(); Expression.Compile(foo, Foo.Bar)(); Expression.Compile(iFoo, IFoo.Bar)(); Expression.CompileToMethod(foo, Foo.Bar); Expression.CompileToMethod(iFoo, IFoo.Bar); MethodInfo.Invoke(foo, Foo.Bar); MethodInfo.Invoke(iFoo, IFoo.Bar);

C#:有什么方法可以跳过多态中的一个基本调用?

class GrandParent { public virtual void Foo() { … } } class Parent : GrandParent { public override void Foo() { base.Foo(); //Do additional work } } class Child : Parent { public override void Foo() { //How to skip Parent.Foo and just get to the GrandParent.Foo base? //Do additional work } } 如上面的代码所示,我如何让Child.Foo()调用GrandParent.Foo()而不是进入Parent.Foo()? base.Foo()将我带到Parent类。

在方法覆盖中更改params修饰符

我知道params修饰符(将数组类型的一个参数转换成所谓的“参数数组”)特别不是方法签名的一部分。 现在考虑这个例子: class Giraffid { public virtual void Eat(int[] leaves) { Console.WriteLine(“G”); } } class Okapi : Giraffid { public override void Eat(params int[] leaves) { Console.WriteLine(“O”); } } 编译时没有任何警告。 然后说: var okapi = new Okapi(); okapi.Eat(2, 4, 6); // will not compile! 给出一个错误( No overload for method ‘Eat’ takes 3 arguments )。 现在,我知道编译器将params修饰符转换为System.ParamArrayAttribute的应用程序到相关参数上。 通常,将一个属性集合应用于虚方法的参数,然后在具有不同属性集的派生类中的重写方法中装饰“对应”参数是没有问题的。 […]

覆盖受保护的内部受保护!

这是一个小时前提出的这个问题的extension 。 在覆盖derived类中的virtual method时,我们无法修改access modifiers 。 考虑System.Web.UI命名空间中的Control类 public class Control : IComponent, IDisposable,… { protected internal virtual void CreateChildControls() { } . . } 现在考虑一下 public class someClass : System.Web.UI.Control { // This should not compile but it does protected override void CreateChildControls() { } // This should compile but it does not protected internal […]