繁体   English   中英

采用该类型的类型和返回实例的通用方法?

[英]Generic Method Taking A Type and Returning Instance of that Type?

我有一堆具有相同属性的模型 - greenPeople,bluePeople等。对于每一个,我都有一个控制器,在帖子中,我将他们的图片推送到某个服务器并创建一个描述该条目的SQL条目。 实际上,我的模型是GreenPeoplePicture,BluePeoplePicture等。

所以我有类似的东西:

GreenPeoplePicture greenPeoplePicture = new GreenPeoplePicture(); 
greenPeoplePicture.Name = "blah"
greenPeoplePIcture.Date = DateTime.UtcNow;

一旦填写完毕,我就会流式传输到远程服务器,然后将“greenPeoplePicture”保存到GreenPeoplePictures表中。 我想为此编写一个通用方法。 我无法绕过如何在不传递任何变量的情况下传递类型本身,因为我想做:

GreenPeoplePicture greenPeoplePicture = new GreenPeoplePicture(); 

在方法中,还有返回类型为GreenPeoplePicture 我相信这篇文章无异于“我不能编码并且不理解泛型”,但我尝试过 - 至少告诉我它是否可行。 MSDN和tutorialspoint没有多大帮助。

像这样的东西?

public T MakeColourPerson<T>() where T : new() {
    return new T();
}

var myPerson = MakeColourPerson<GreenPeoplePicture>();

此外,如果GreenPeoplePictureBluePeoplePicture有任何共同点(例如,如果它们从ColourPeoplePicture继承,您可以更改其位置:

where T : ColourPeoplePicture, new()更精确

这将允许您在MakeColourPerson做更多有用的事情

public T MakeColourPerson<T>() 
    where T : ColourPeoplePicture, new() 
{
    var colourPerson = new T();
    colourPerson.Name = "blah";
    colourPerson.Date = DateTime.UtcNow;
    return colourPerson;
}

假设ColourPeoplePicture公开属性NameDate

对于泛型,可以使用default(T)将变量初始化为默认值,也可以使用new T()创建实例。 为了使用new() ,你应该通过添加new()的类型约束来缩小类型的特异性。

public T Factory<T>() where T : new() {
    return new T();
}

要么

    return default(T);

如果你想处理每种类型的不同属性,那么泛型将无法完全解决这个问题,你必须用反射来补充它以动态地查找属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM