我有不同的类,它们共享一些具有相同类型和名称的属性。我希望彼此分配相同的属性值。我在以下伪代码的注释中更好地解释了我的意图。在C#中可以吗?
考虑到有很多共同的属性,但是在不相关的类中,我们必须一一对应地分配它们吗?
第二种情况是共享相同的属性,但是其中一些可能为空,谁知道!
侧面说明:这些类已经存在,不能更改,修改。 Kinda sealed
。
不能使用nameof
操作符和两个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;
*/
}
}
}
答案 0 :(得分:1)
基于问题中的评论,这只是为了展示如何通过反思来完成。
免责声明,这只是有关如何使用反射来同步属性的非常简化的示例。它不处理任何特殊情况(修饰符,只读,类型不匹配等)
我强烈建议使用自动映射器来实现qp目标。
public class Type1
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
public class Type2
{
public string Property1 { get; set; }
public string Property3 { get; set; }
}
class Program
{
static void Main(string[] args)
{
var t1 = new Type1 { Property1 = "Banana" };
var t2 = new Type2();
var properties1 = typeof(Type1).GetProperties().ToList();
var properties2 = typeof(Type2).GetProperties().ToList();
foreach(var p in properties1)
{
var found = properties2.FirstOrDefault(i => i.Name == p.Name);
if(found != null)
{
found.SetValue(t2, p.GetValue(t1));
}
}
Console.WriteLine(t2.Property1);
}
}
答案 1 :(得分:0)
简单的答案是,应用OOP。定义一个基础Food
类,并在您拥有的任何特定食物类中继承它。您可以将所有共享道具放在基类中。
public class Food
{
public string food2 { get; set; }
// other shared stuff
}
class GrandpaFood : Food
{
// other specific stuff
}
答案 2 :(得分:0)
正如其他人所说,使用某些面向对象的属性,例如继承实现接口的超类。
如果要继承,请考虑使超类(继承自的超类)抽象。这意味着超类本身无法实例化,从而大大降低了违反Liskov替代原理的风险。而且它通常可以更好地反映实际问题。在您的示例中,情况也是如此,因为“食物”不是现实世界中的实际事物,而是一组事物。