简体   繁体   English

我可以使用invoke抽象类方法吗

[英]can I use invoke to abstract class method

As below code i just want to know can I use Invoke() for abstract class 如下面的代码我只想知道我可以对抽象类使用Invoke()

public abstract class genericDefine
{
    public void Foo<T>(T item)
    {
        Console.WriteLine(typeof(T).Name);
    }
}

var bar = typeof(Bar);
var fooMethod = typeof(genericDefine).GetMethod("Foo");
var fooOfBarMethod = fooMethod.MakeGenericMethod(new[] { bar });
fooOfBarMethod.Invoke(new genericDefine(), new object[] { new Bar() });

I also tried for use Derived class object but it wont work for me....! 我也尝试使用Derived类对象,但它对我不起作用....!

You either have to make the method static, or pass in an instance to call the method on. 您要么必须使该方法静态化,要么传入一个实例以调用该方法。 You can't call an instance method without actually having an instance (and you can't instantiate an abstract class). 如果没有实际的实例,就不能调用实例方法(也不能实例化抽象类)。

So either this (using an instance): 所以这(使用实例):

public class genericDefineInstance : genericDefine
{ }


...
fooOfBarMethod.Invoke(new genericDefineInstance(), new object[] { new Bar() });

Or (using an static method): 或(使用静态方法):

public static void Foo<T>(T item)
{
    Console.WriteLine(typeof(T).Name);
}

...
fooOfBarMethod.Invoke(null, new object[] { new Bar() });

In order to invoke the MethodInfo without passing in an instance of the object you need to have that method defined as static . 为了在不传入对象实例的情况下调用MethodInfo ,您需要将该方法定义为static So if your method was defined as such it does work. 因此,如果您的方法是这样定义的,那么它确实可以工作。 Otherwise you need to have an subclass instance of the abstract base class. 否则,您需要具有抽象基类的子类实例。

 public abstract class AbstractClass
 {
     public static void Foo<T>(T item)
     {
         Console.WriteLine(typeof(T).Name + ": " + item);
     }
 }

But then why have the class be abstract ? 但是,为什么类是abstract呢?

  1. You either need an instance from a class that inherits the abstract class 您要么需要继承abstract类的类的实例,
  2. Or, you need to make the method static -- which defeats the purpose of abstract classes 或者,您需要使该方法static -这违背了abstract类的目的

Here is the .NET fiddle. 这是.NET小提琴。

No you can not. 你不能。 To call your method, you still need an instance of the class, and you can't create an instance of an abstract class. 要调用您的方法,您仍然需要一个类的实例,并且不能创建抽象类的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM