【发布时间】:2018-09-20 07:30:28
【问题描述】:
我与一位父母有一些 DTO。该父级具有创建其任何子级的通用方法(使用反射)。每个 DTO 都有配置(字典)。我可以通过创建方法中的参数传递字典,但每个子类型都具有相同的配置,所以我想将其设为静态并存储在子项中。我在这里发现:Accessing a static property of a child in a parent method 这可能是一个错误的设计。是我的情况吗?我必须通过参数传递配置还是将其存储在其他地方?
例子:
public class Parrent
{
public static T Create<T>(string[] fields, Dictionary<string, bool> config)
where T : Parrent
{
var result = Activator.CreateInstance<T>();
// filling fields using config
return result
}
}
编辑:
以下是配置的工作原理:
public class Child1 : Parrent
{
public string Child1String;
public DateTime Child1DateTime;
}
public class Child2 : Parrent
{
public int Child2Int;
public string Child2String;
public TimeSpan Child2TimeSpan;
}
和字典(它说明我可以忽略哪些字段(例如,因为它们将为空)并且它是在配置文件中的处理类中设置的):
- Child1:
"Child1String": true,
"Child1DateTime": true,
- Child2
"Child2Int": true,
"Child2String": false,
"Child2TimeSpan": true,
【问题讨论】:
-
旁注:为什么不是
where T : Parrent, new()然后var result = new T();而不是Activator.CreateInstance<T>()? -
@DmitryBychenko 对,我可以改变它。忘了它。谢谢:)
-
" 但是每个子类型都有相同的配置" 这到底是什么意思?每个孩子对于同一组属性具有相同的初始值?
-
@MongZhu 是的。假设我有
public class Child1 : Parrent和public class Child2 : Parrent那么 Child1 的每个实例都有相同的配置字典,而 Child2 的每个实例都有相同的配置字典,但与 Child1 不同。 -
“每个子类型都有相同的配置”和“但与 Child1 不同”让我有点困惑。字典有什么用?它是否包含字段名称和相应的值?请发布 2 个孩子的示例以及这本词典的内容可能是什么样的
标签: c# dictionary inheritance dto