【发布时间】:2020-01-01 06:37:15
【问题描述】:
我有不同的类共享一些相同类型和名称的属性。我希望彼此分配相同的属性值。我在下面的伪代码中用 cmets 更好地解释了我的意图。在 C# 中可以吗?
想一想,有很多共同的属性,但在不相关的类中,我们是否必须一一分配它们?
第二种情况是共享相同的属性,但其中一些可能是空的,谁知道呢!
旁注:类已经存在,无法更改,无法触摸。有点像sealed。
不能使用nameofoperator 和两个for循环来完成吗?如果匹配,比较属性名称,分配?
using System;
namespace MainProgram
{
class HomeFood
{
public DateTime Date { get; set; }
public string food1 { get; set; }
public string food2 { get; set; }
public int cucumberSize { get; set; }
}
class AuntFood
{
public string food2 { get; set; }
public int cucumberSize { get; set; }
public DateTime Date { get; set; }
public string food1 { get; set; }
// extra
public double? length { get; set; }
}
class GrandpaFood
{
public string? food2 { get; set; }
public int cucumberSize { get; set; }
public DateTime? Date { get; set; }
public string food1 { get; set; }
// extra
}
static class Program
{
public static void Main(string[] args)
{
var home = new HomeFood
{
Date = new DateTime(2020, 1, 1),
food1 = "cucumber",
food2 = "tomato",
cucumberSize = 123
};
var aunt = new AuntFood();
/*
First case: same types
Expected for-each loop
assigning a class's property values
to other class's property values
or for-loop no matter
foreach(var property in HomeFood's properties)
assign property's value to AuntFood's same property
*/
var home2 = new HomeFood();
var grandpa = new GrandpaFood
{
Date = new DateTime(2020, 1, 1),
food1 = "dfgf",
food2 = "dfgdgfdg",
cucumberSize = 43534
};
/*
Second case: similar to first case
with the exception of same type but nullable
or for-loop no matter
foreach(var property in GrandpaFood's properties)
assign property's value to GrandpaFood's same property
we don't care if it is null e.g.
Home2's same property = property's value ?? default;
*/
}
}
}
【问题讨论】:
-
为什么不使用枚举属性 FoodType 创建一个类
Food? -
automapper 可以帮你做到这一点
-
@Charles 该示例仅用于说明目的。想一想你有不同的sql列,用属性表示,涉及到生成的两个不同的类,不能碰,能不能提出你的枚举思路?
-
@snr 我也建议使用 automapper,但如果您不想使用库,也可以使用反射实现同样的效果
-
@gsharp 不能用nameof操作符和两个for循环来完成吗?如果匹配,比较属性名称,分配?