使用C#中的Generics创建具有内容的类似类型的实例

时间:2015-11-03 14:26:51

标签: .net generics

我有两个不同的类定义C1和C2,它们都有一个叫做的属性     DateTime开始;

所以

public partial class C1
{
    public DateTime Start;
}
public partial class C2
{
    public DateTime Start;
}

因为这两个类有点相似,所以我想要一种聪明的方法来创建这些类的实例,我想是否可以将它组合在一个泛型方法中,该方法返回上述类之一的实例分配的Start属性: 我想的是:

public T GetClassInstance<T>(DateTime start) where T : new()
{
    T time = new T();
    time.Start = start;
    return time;
}

但上面给出了编译错误,因为没有定义T.Start。

我知道我可以添加约束,但只适用于一个类:

public T GetClassInstance<T>(DateTime start) where T : C1, new()

但如果我在那里添加更多课程,我会收到编译错误。

此外,我无法重新定义我的类来实现一个通用接口,因为它们是从XSD生成的,我可能无法编辑

对智能方式有任何建议我可以实现上述目标吗?

由于 Jeeji

2 个答案:

答案 0 :(得分:1)

定义界面

guide

ggplot(df, aes(x = x, y = y), alpha = 0.7) + geom_point(data = subset(df, !is.na(P)), aes(size = P, color = Te)) + geom_point(data = subset(df, is.na(P)), color = "black") + scale_colour_gradient(low = "#00FF33", high = "#FF0000") + labs(x = "x", y = "y", colour = "T", size = "P") + scale_size(range = c(3, 8)) + theme_bw(base_size = 12, base_family = "Helvetica") + theme(panel.grid.minor = element_line(colour = "grey", size = 0.5), axis.text.x = element_text(angle = 45, hjust = 1), legend.position = "bottom", legend.box = "horizontal") + guides(colour = guide_colourbar(title.position = "top", title.hjust = 0.5), size = guide_legend(title.position = "top", title.hjust = 0.5)) public interface IHasStartTime // please think of a more descriptive name! { DateTime Start {get;set;} } 上实施,并将其用作约束

C1

答案 1 :(得分:1)

使用界面作为其他建议。生成的类通常是一个部分类,在你的情况下它是否部分?因此,您可以在部分部分中添加接口实现,而不是在生成的代码中添加。

以下是一个例子:

public partial class C1
{
    public DateTime Time { get; set; }
}
public partial class C2
{
    public DateTime Time { get; set; }
}

public interface IClass
{
    DateTime Time { get; set; }
}

public partial class C1 : IClass { }
public partial class C2 : IClass { }

static T SetTime<T>(DateTime time) where T: IClass, new()
{
    var t = new T();
    t.Time = DateTime.Now;
    return t;
}