我有两个对象,我想将它们合并:
public class Foo
{
public string Name { get; set; }
}
public class Bar
{
public Guid Id { get; set; }
public string Property1 { get; set; }
public string Property2 { get; set; }
public string Property3 { get; set; }
public string Property4 { get; set; }
}
创建:
public class FooBar
{
public string Name { get; set; }
public Guid Id { get; set; }
public string Property1 { get; set; }
public string Property2 { get; set; }
public string Property3 { get; set; }
public string Property4 { get; set; }
}
我只能在运行时获得Foo的结构。Bar在运行时可以是任何类型。我想要一个方法,它将给定的类型与Foo组合起来。例如,在上面的场景中,该方法在运行时被赋予了一个Bar类型,并将其与Foo组合在一起。
最好的方法是什么?可以使用LINQ表达式来实现吗?还是必须动态生成?或者有其他方法?我仍在学习C# 3.0中的新LINQ命名空间,所以如果不能使用LINQ表达式,请原谅我的无知。这也是我第一次在C#中做像这样动态的事情,所以我不太确定所有可用的选项。
感谢提供的任何选项。
编辑
这仅适用于向给定给我的类型添加元信息,以进行序列化。在进行序列化之前,此方案使用户的对象不了解需要添加的元信息。在询问此问题之前,我想出了两个选项,我只是想看看是否还有更多选项,然后再决定使用哪一个。
我想出的两个选项是:
通过添加元信息操作我得到的类型的序列化字符串。
封装给我的类型,这类似于Zxpro提到的,但我的略有不同,这没关系。这只会让我的API的用户遵循约定,这不是坏事,因为人人都追求约定优于配置。
public class Foo<T>
{
public string Name { get; set; }
public T Content { get; set; }
}
编辑
感谢大家的回答。我决定像上面那样包装对象,然后将答案给了@Zxpro,因为大多数人也喜欢这种方法。
如果有其他人遇到这个问题,请随时发布,如果您认为可能有更好的方法。