c# - 如何使用类本身作为方法参数?

标签 c# class methods

已经有一段时间了,但我需要将一些自定义代码转换为 C#(我认为它被称为 Jade 或其他人给我的东西)。有一个特定的方法接受一个类(任何没有任何对象转换的类)。这是我要转换的代码。

      class  management
        Accessor current_class
        Accessor class_Stack

      def call(next_class)          #method, called global, takes a "class" instead 
                                       #of a variable, kinda odd
        stack.push(current_class)      #stack handling
        current_class = next_class.new #makes a new instance of specified next_class

      end
    end

next_class 似乎是与基类相关的任何类,并将它们的新实例分配给名为 currentClass 的变量。还有其他“方法”可以做类似的事情。我试过将参数类型设置为“object”,但丢失了所有需要的“next_class”属性。这是我的尝试

     public class management {
        public Stack stack;           
        public Someclass currentClass; 

      public void Call(object nextClass) {
        stack.push(currentClass);   // stack handling    
        currentClass = new nextClass(); // conversion exception, otherwise loss of type

    }
    }

这在 C# 中是否可行 另一件事,当您将子类转换为基类时,这种语言似乎能够保留子类的属性(也包括方法)。例如,将绿色自行车转换为自行车,但它仍然是绿色的

有人能给我指出正确的方向吗?还是我需要重写它并改变它做事的方式?

最佳答案

你想要的是泛型,我也认为,基于你调用方法的事实,接口(interface)。

因此您的接口(interface)将定义“new”,类将从该接口(interface)继承。

然后您可以将该类作为泛型传递,并在其上调用“new”的接口(interface)方法。

所以;

public interface IMyInterface
{
  void newMethod();
}

public class MyClass1 : IMyInterface
{
    public void newMethod()
    {
      //Do what the method says it will do.
    }
}

public class Class1
{
    public Class1()
    {
        MyClass1 classToSend = new MyClass1();
        test<IMyInterface>(classToSend);
    }

    public void test<T>(T MyClass) where T : IMyInterface
    {
        MyClass.newMethod();
    }
}

编辑

并查看 C# 4.0 中的“动态”。我这样说是因为如果您直到运行时才知道该方法是什么,您可以将其定义为动态的并且您基本上是在告诉编译器“相信我该方法会在那里”。

这是为了防止您不能使用泛型,因为您调用的方法对于每个类都是不同的。

关于c# - 如何使用类本身作为方法参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16184014/

相关文章:

c# - Socket.UseOnlyOverlappedIO?

c# - 即使未调用引用的 DLL,是否可以加载它?

c# - 由于 C# 中的特定构造函数而导致的可变类属性

C++ 继承和虚函数

ruby - #<EventManager :0x007fa4220320c8> (NoMethodError) 的未定义方法 `output_data'

c# - IIS 下的多个端点

c# - 需要正则表达式来满足密码要求

python - 类属性与方法参数性能? Python

javascript - 将多个/未知数量的变量传递给 JavaScript 参数?

function - 在内部也调用外部(即接口(interface))函数吗?