具有默认数据的通用对象创建方法

我想在一个将由其他类转换的类中进行两个简单的调用。就像是:


ObjectCreator.CreateBlank<Human>();

ObjectCreator.CreatePopulated<Human>();

ObjectCreator.CreateBlank<Dog>();

ObjectCreator.CreatePopulated<Dog>();

我目前这样做:


public class ObjectCreator

{

    public static T CreateBlank<T>()

    {

        return Activator.CreateInstance<T>();

    }


    public static T CreatePopulated<T>()

    {

        //Somehow return new object with populated properties

    }

}

我正在努力解决人口稠密的部分。我希望它返回具有定义属性的该类型的“默认”对象。我已经尝试了一些涉及传入接口的事情,但它很快就会变得混乱(我也不希望这会特别干净)


因此,如果我调用 ObjectCreator.CreatePopulated(),我希望它以某种方式转到一个不同的类,在那里我创建一个新的 Anything,并将其属性填充为特定值。感觉就像我很接近但在这里遗漏了一块拼图。


我的最终目标是让调用尽可能简单/易读。任何帮助表示赞赏。


我确实意识到简单地调用一个创建和填充每个对象的类可能会更容易,但这对我来说是一个学习练习,我想尝试让它尽可能通用。


守着一只汪
浏览 117回答 1
1回答

森林海

我会建议做这样的事情:public interface IPopulatable{&nbsp; &nbsp; void Populate();}public class ObjectCreator{&nbsp; &nbsp; public static T CreateBlank<T>() where T : new ()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return new T();&nbsp; &nbsp; }&nbsp; &nbsp; public static T CreatePopulated<T>() where T : IPopulatable, new()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var populatable = new T();&nbsp; &nbsp; &nbsp; &nbsp; populatable.Populate();&nbsp; &nbsp; &nbsp; &nbsp; return populatable;&nbsp; &nbsp; }}public class Human : IPopulatable{&nbsp; &nbsp; public string Name { get; set; }&nbsp; &nbsp; public void Populate()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Name = "Joe";&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP