【问题标题】:How to read class Properties without instantiation?如何在没有实例化的情况下读取类属性?
【发布时间】:2022-12-03 21:53:02
【问题描述】:

How can i read all class Properties, without having an instantiated object of this Class nor hard-coding the name of the class itself? The name of the class is dynamically, stored as a string in a variable.

(As classes are added independentely of the developer of the function above, the code of the function won\'t be extended by \"switch-case\" for every new Class)

Unfortunately, the following Code...

// first part ist just to explan and won\'t be available in the code... the content of modelClass will unknown
MyModel mod = new();
string modelClass = mod.GetType().ToString();
//
Console.WriteLine(\"Class of Model is: {0}\", modelClass );
PropertyInfo[] myPropertyInfo;
myPropertyInfo = Type.GetType(modelClass).GetProperties();

throws an ...

fail: Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost[111]
      Unhandled exception in circuit \'Vir-nbPwhGHcOpSjnVvTlz4-11RtlEirY2qypkNIPw8\'.
      System.NullReferenceException: Object reference not set to an instance of an object.

The Console Output confirms, the right Class has been used. But i am confused, as i thought GetProperties() doesn\'t need an concrete Object.


Using the Object directly, works without problem

myPropertyInfo = mod.GetType().GetProperties();

Also typeof() seems close to what i\'m looking for. But it looks as i can\'t pass a Variable which contains the String of the desired Class. Then, typeof() determines the type of the Variable i pass

    标签: c# .net


    【解决方案1】:
    【解决方案2】:
    猜你喜欢
    • 1970-01-01
    • 2015-07-19
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多