大家好, 我将创建一个方法,该方法将需要任何自定义类引用(而不是对象)才能执行.
Hi All, I am going to create a method which will require any custom class reference (not object)to Execute.
class A { } class B { } class C { pubilc void RunTimeMethod(Parameter) // Here I want to accept Class A or Class B as parameter at runtime { // Method is working fine if enter I use RuntimeMethod(A obja). But It can be any one class } } class D:C { //C objC = new C(); RunTimeMethod(class); // Here I want to pass Class A or Class B as parameter at runtime //RuntimeMethod(A) working fine. }那么,如何在创建和调用方法时定义传递给方法的类? 问候! Aman
So, How to define pass class to method while creating and calling it? Regards! Aman
推荐答案尝试: public static void RunSnippet() { Button b = new Button(); Console.WriteLine(myMethod<Button>(b)); } public static string myMethod<T>(T t) where T : Control { return t.ToString(); }
这个想法不是很有用,只是因为这些类之间的共同点很少:只有System.Object作为共同的基类.答案取决于您可以在RunTimeMethod中执行的操作.不多.您只能调用System.Object的方法. 看起来像这样: This is not very useful idea simply because the classes has very little in common: only System.Object as a common base class. The answer depends on what you can do in RunTimeMethod. Not many. You can only call methods of System.Object. It would look like this: internal void RunTimeMethod<T>(T t) where T: new() //the "new" above will guarantee a class with parameter-less constructor { //... }
作为一种更高级的方法,您可以使用Reflection并找出一些通用的构造函数.但是,对于任何参数类都要求有一些通用接口并将其置于通用约束中,这会更加健壮.
As a more advanced approach, you can use Reflection and find out some general purpose constructor. But it''s much more robust to demand some common interface for any of the parameter classes and put it in a generic constraint.
internal interface IGenericParameterClass { /*...*/ } internal class A : IGenericParameterClass { /*...*/ } internal class B : IGenericParameterClass { /*...*/ } internal void RunTimeMethod<T>(T t) where T: IGenericParameterClass, new() //the IGenericParameterClass above will a generic parameter with common interface to use //in this function { // }另外,考虑使用经典的OOP或基于接口的方法.您可能正在尝试在方法中严重滥用OOP.想一想. 另外,如果您可以解释所有此活动的最终目标,则有机会获得更好的建议.
Also, think about using classic OOP or interface-based approach. You might be trying to heavily abuse OOP in your approach. Just think about it. Also, if you can explain the ultimate goal of all this activity, you can get a chance to get better advice.
以下是上述示例的答案 A级 { } B级 { } C级 { pubilc void RunTimeMethod< T>(),其中T:class { } } D级:C { B objB = new B(); if(objB == null) { RunTimeMethod< A>(); } 其他 { RunTimeMethod< B>(); } } Here is an answer with above example class A { } class B { } class C { pubilc void RunTimeMethod<T>() where T: class { } } class D:C { B objB = new B(); if(objB==null) { RunTimeMethod<A>(); } else { RunTimeMethod<B>(); } }
更多推荐
在运行时将任何自定义类作为参数传递给方法
发布评论