问题描述
假设我有许多不同的程序员开发的类,所以我不能更改他的代码.所有这些类都具有相同的构造函数,并且它们都是从相同的基类派生的.
我想修改此类的基本构造函数(但我不能).有没有一种方法可以重用此类,而无需直接更改它们,而是使用其他构造函数.例子:
suppose I have many classes developed by a different programmer, so that I cannot change his code. All these classes has the same constructor and they are all derived from the same base class.
I would like to modified the base constructor of this classes (but I can''t). Is there a way to reuse this classes without changing them directly, but using a different constructor. An example:
class A
{
public A(List<double> a) { }
}
class A1: A
{
public A1(List<double> a):base(a) { }
}
class A2:A
{
public A2(List<double> a):base(a) { }
}
我不能更改A,A1,A2类.我想使用它们允许接受double []而不是List< double>作为构造函数.我不想每次都包装.
I can''t change classes A, A1, A2. I want to use them allowing to accept double[] instead of List<double> as constructor. I dont want to wrap each time. Is there a design solution?
推荐答案
//using System.Reflection;
public static class Wrapper
{
// where clause ensures that it only works for the A class and it's derived classes
public static T CreateA<T>(double[] a) where T : TheOriginalClasses.A
{
// Get the cconstructor
Type[] types = new Type[1];
types[0] = typeof(List<double>);
ConstructorInfo constructorInfo = typeof(T).GetConstructor(types);
// Invoke the constructor
object[] objects = new object[1];
objects[0] = a.ToList();
T value = constructorInfo.Invoke(objects) as T;
return value;
}
}
您可以将其称为以下代码:
You can call this which the following code:
double[] a = new double[3] { 0.5, 1.1, 2.5 };
var testA = Wrapper.CreateA<TheOriginalClasses.A>(a);
var testA1 = Wrapper.CreateA<TheOriginalClasses.A1>(a);
var testA2 = Wrapper.CreateA<TheOriginalClasses.A2>(a);
Console.WriteLine(testA.GetType().ToString());
Console.WriteLine(testA1.GetType().ToString());
Console.WriteLine(testA2.GetType().ToString());
我不确定这段代码是否会赢得一次代码选美大赛,但是它将为您提供通用包装器.缺点可能是由于使用了反射而导致的性能损失.
I''m not sure if this code will win a code beauty contest, but it will give you a generic wrapper. A disadvantage might be performance loss due to using Reflection.
这篇关于包装不同程序员的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!