Dynamically create an object of

前端 未结 6 1443
时光说笑
时光说笑 2020-12-02 16:40

I have a table in my database that I use to manage relationships across my application. it\'s pretty basic in it\'s nature - parentType,parentId, childType, childId... all a

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 17:29

    If the type is known by the caller, there's a better, faster way than using Activator.CreateInstance: you can instead use a generic constraint on the method that specifies it has a default parameterless constructor.

    Doing it this way is type-safe and doesn't require reflection.

    T CreateType() where T : new()
    {
       return new T();
    }
    

提交回复
热议问题