Generic constructor with new type constraint

后端 未结 1 1186
囚心锁ツ
囚心锁ツ 2021-01-20 06:00

I have 2 types of objects, Database models and normal system models.

I want to be able to convery the model into Database model and vice versa.

I have the fo

相关标签:
1条回答
  • 2021-01-20 06:24

    To use new on a generic type, you would have to specify the new() constraint on your class/method definition:

    public static E FromModel<T, E>(T other) 
            where T : sysModel
            where E : dbModel, new()
    

    Since you are using a parameter in the constructor, you can't use new, but you can use the Activator instead and pass other as an argument:

    public static E FromModel<T, E>(T other)
        where T : sysModel
        where E : dbModel
    {
        return (E)Activator.CreateInstance(typeof(E), new[]{other});
    }
    
    0 讨论(0)
提交回复
热议问题