且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在运行时将任何自定义类作为参数传递给方法

更新时间:2021-12-26 02:36:11

尝试:
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.想一想.

另外,如果您可以解释所有此活动的最终目标,则有机会获得更好的建议.

—SA




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.

—SA


以下是上述示例的答案

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>();
}
}