0
如何修改附加到某个Type
的TypeAttributes
?如何更改类型的属性?
我想修改一个类型并通过应用TypeAttributes.Abstract
标志将其抽象化,我该怎么做?我确定我需要在某个地方调用CLR,但是我无法追踪它从哪里得到这个信息,它似乎是一个无休止的分层方法调用其他方法的系统。
如何修改附加到某个Type
的TypeAttributes
?如何更改类型的属性?
我想修改一个类型并通过应用TypeAttributes.Abstract
标志将其抽象化,我该怎么做?我确定我需要在某个地方调用CLR,但是我无法追踪它从哪里得到这个信息,它似乎是一个无休止的分层方法调用其他方法的系统。
您可以使用库(如Mono.Cecil)以编程方式更改类型。 假设您在名为“ExistingAssembly.dll”的程序集中有名为“Test”的类,并且希望将类“Test”变成抽象类。 你现在需要做的是:
void Main(){
//This is the existing assembly containing the type that you wish to modify
var assemblyFile = @"C:\temp\ExistingAssembly.dll";
var ass = Mono.Cecil.AssemblyDefinition.ReadAssembly(assemblyFile);
var type = ass.MainModule.GetTypes().First(t => t.Name == "Test");
//Make the type an Abstract type (class)
type.IsAbstract = true;
//Finally save the modified assembly into a new file
ass.Write(@"C:\temp\ModifiedAssembly.dll");
//The type "Test" in the above "ModifiedAssembly.dll" is now an abstract class.
}
// This is the Type that you wish to turn into an Abstract Class
public class Test {
public string DummyMethod(){
return "Dummy Return";
}
}
您可以从这里得到的Mono.Cecil能组件(的NuGet): https://www.nuget.org/packages/Mono.Cecil/
要修改现有的类型是一个有趣的欲望...什么是你如果你能分享它的最终目标? –
据我所知,你不能修改现有的类型。你可以发出一个新的类型,但它可以复制现有的类型,但可能会非常复杂。你为什么想要这样做呢? – poke
@Alexei我需要防止某种类型在任何情况下被实例化。 – AlphaModder