如何从.NET中使用反射一个密封类继承?反射、NET

2023-09-04 00:52:16 作者:香煙ㄨ吥離手

在你开始解雇我,我不希望这样做,但有人在another帖子说,这是可能的。这怎么可能?我从来没有听说过使用反射的东西继承的。但我已经看到了一些奇怪的事情...

Before you start firing at me, I'm NOT looking to do this, but someone in another post said it was possible. How is it possible? I've never heard of inheriting from anything using reflection. But I've seen some strange things...

推荐答案

无虚函数覆盖,有没有在子类密封类多点。

Without virtual functions to override, there's not much point in subclassing a sealed class.

如果你试图在它的虚拟函数写一个密封类,将得到以下编译器错误:

If you try write a sealed class with a virtual function in it, you get the following compiler error:

// error CS0549: 'Seal.GetName()' is a new virtual member in sealed class 'Seal'

不过,您可以通过声明他们在一个基类(像这样)获得虚拟功能于密封类,

However, you can get virtual functions into sealed classes by declaring them in a base class (like this),

public abstract class Animal
{
	private readonly string m_name;

	public virtual string GetName() { return m_name; }

	public Animal( string name )
	{ m_name = name; }
}

public sealed class Seal : Animal
{
	public Seal( string name ) : base(name) {}
}

问题仍然存在,虽然,我看不出你如何能偷偷过去的编译器,让您声明一个子类。我尝试使用IronRuby的(红宝石是所有hackety语言hackiest),但即使它不会让我。

The problem still remains though, I can't see how you could sneak past the compiler to let you declare a subclass. I tried using IronRuby (ruby is the hackiest of all the hackety languages) but even it wouldn't let me.

在密封的部分嵌入到MSIL,所以我猜想,在CLR本身其实强制这一点。你必须加载code,dissassemble情况下,将密封位,然后重新组装,并加载了新的版本。

The 'sealed' part is embedded into the MSIL, so I'd guess that the CLR itself actually enforces this. You'd have to load the code, dissassemble it, remove the 'sealed' bit, then reassemble it, and load the new version.