Is it possible to create an instance of an class without running ANY code from the class? (no ctor, no field initializations)

眉间皱痕 提交于 2019-12-05 07:17:25

Simply:

var obj = (myclass)FormatterServices.GetUninitializedObject(typeof(myclass));

That will not run the constructor / field initializers. At all. It will not run the constructor for someotherclass; name will be null.

It will, however, execute any static constructor that exists, if necessary under standard .NET rules.

HOWEVER! I should note that this method is not intended for ad-hoc usage; its primary intent is for use in serializers and remoting engines. There is a very good chance that the types will not work correctly if created in this way, if you have not subsequently taken steps to put them back into a valid state (which any serializer / remoting engine would be sure to do).

As an alternative design consideration:

[SomeFeature("ANiceConstString")]
public class myclass : myinterface {

  public someotherclass name = new someotherclass()

  public myclass() {
     //Unknown code
  }
}

Now you can access the feature without instantiation; just use:

var attrib = (SomeFeatureAttribute)Attribute.GetCustomAttribute(
    type, typeof(SomeFeatureAttribute));
string whatever = attrib == null ? null : attrib.Name;

with:

[AttributeUsage(
    AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum)]
public sealed class SomeFeatureAttribute : Attribute
{
    private readonly string name;
    public string Name { get { return name; } }
    public SomeFeatureAttribute(string name) { this.name = name; }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!