在运行时与另一个基类更改/交换基类 [英] Change/Swap base class at runtime with another base class
问题描述
听起来像个愚蠢的主意,但我想知道是否有可能。
Sounds like silly idea but I was wondering if it's possible somehow.
是否可以在运行时更改派生类的基类?当然,有很多假设,还有为什么有人会这样做的问题以及它的不良设计等等。
Is it possible to change the base class of a derived class at runtime? Of course, there are lot of ifs and buts and the the question of why would someone do it and its a bad design probably and all that.
把所有这些都放在一边(即使它们可能是完全有效的),也可以说,只是为了踢球或显示你的书呆子,是否可以用C#或任何语言编写
Keeping all those aside (even though they might be perfectly valid), let's say, just for kicks or to show your nerdiness, is it possible in C# or any language for that matter?
是这样的:
public class baseOriginal {
public string justAProperty;
}
public class baseSwapped {
public int sillyNumber;
}
public class derivedClass : baseOriginal {
public bool iAmDumb;
}
void Main() {
baseOriginal derived = new derivedClass ();
Console.WriteLine(derived.justAProperty);
baseSwapped derivedSwapped = (??);
Console.WriteLine(derivedSwapped.sillyNumber);
}
推荐答案
我能想到的最接近的东西的内容如下:
The closest thing I can think of is the following:
http://msdn.microsoft.com/zh-cn/library/dd264736.aspx
static void Main(string[] args)
{
ExampleClass ec = new ExampleClass();
// The following line causes a compiler error if exampleMethod1 has only
// one parameter.
//ec.exampleMethod1(10, 4);
dynamic dynamic_ec = new ExampleClass();
// The following line is not identified as an error by the
// compiler, but it causes a run-time exception.
dynamic_ec.exampleMethod1(10, 4);
// The following calls also do not cause compiler errors, whether
// appropriate methods exist or not.
dynamic_ec.someMethod("some argument", 7, null);
dynamic_ec.nonexistentMethod();
}
class ExampleClass
{
public ExampleClass() { }
public ExampleClass(int v) { }
public void exampleMethod1(int i) { }
public void exampleMethod2(string str) { }
}
我不知道动态语言运行时是否可以执行您想要的操作。
I have no idea if the dynamic language runtime can do what you want it to do.
通过将至少一个
定义为一个接口,然后将从一个类型派生到另一个的
转换,可以得到从这两种类型派生的
。
Closest you could get would be to derive from both types by defining at least one as an interface, then casting derived from one to the other.
根据这个建议可以满足他想要做的事的例子,我将不得不同意,这也是他实际想要做的一个更好的设计。
I would have to agree, based on the example this suggestion would satisfy what he wants to do, it also is a better design then what he actually wants to do.
这篇关于在运行时与另一个基类更改/交换基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!