【问题标题】:Static child field in parent's method父方法中的静态子字段
【发布时间】: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&lt;T&gt;()
  • @DmitryBychenko 对,我可以改变它。忘了它。谢谢:)
  • " 但是每个子类型都有相同的配置" 这到底是什么意思?每个孩子对于同一组属性具有相同的初始值?
  • @MongZhu 是的。假设我有public class Child1 : Parrentpublic class Child2 : Parrent 那么 Child1 的每个实例都有相同的配置字典,而 Child2 的每个实例都有相同的配置字典,但与 Child1 不同。
  • “每个子类型都有相同的配置”和“但与 Child1 不同”让我有点困惑。字典有什么用?它是否包含字段名称和相应的值?请发布 2 个孩子的示例以及这本词典的内容可能是什么样的

标签: c# dictionary inheritance dto


【解决方案1】:

一个类不应该假设它的继承者除了它在类型定义中明确规定的任何东西。

使用反射绝对是一种“代码味道”,因此父母可以与其孩子进行交互。这听起来像是一种将静态设计问题推到运行时的方法。

如果您想用一些配置填充子项,您需要确保这些属性存在于它们的实现中。或者,您可以委托孩子们将配置方法抽象化。将 virtual 用于两者的组合。

public class Parent
{
    public string PropertyParentControls { get; protected internal set; }

    static internal T ReadConfigItem<T>(
            string name,
            IReadOnlyDictionary<string, dynamic> configuration)
    {
        if (configuration.TryGetValue(name, out var configValue))
        {
            return configValue; 
        }
        else
        {
            return default(T);
        }
    }

    virtual internal void FillConfig(IReadOnlyDictionary<string, dynamic> configuration)
    {
        this.PropertyParentControls =
            ReadConfigItem<string>("PropertyParentControls", configuration);    
    }   
}

public sealed class Child : Parent
{
    public int PropertyChildControls { get; private set; }

    override internal void FillConfig(IReadOnlyDictionary<string, dynamic> configuration)
    {
        base.FillConfig(configuration); // because the Child wants the Parents help.
        this.PropertyChildControls = 
            ReadConfigItem<int>("PropertyChildControls", configuration);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多