缩短语法以获得几乎相同的属性

时间:2019-04-15 14:22:45

标签: c# properties

我不得不重做一些代码,偶然发现了几个定义了大量非常相似属性的类。

它们看起来像这样:

public _ReturnType _PropertyName
{
    get
    {
        IMarkerInterface value = null;
        if (Properties != null) Properties.TryGetValue(_string, out value);
        return value as _ReturnType;
    }
    set { Properties[_string] = value; }
}

它们之间的唯一区别是_ReturnType,字典_string中使用的Properties,显然还有_PropertyName

我想知道是否有一种缩短语法的方法?

3 个答案:

答案 0 :(得分:0)

如果看到重复的代码,则提取一个方法。看起来像这样:

private T GetValueOrDefault<T>(string key)
{
    IMarkerInterface value = null;
    if (Properties != null) Properties.TryGetValue(key, out value);
    return value as T;
}

然后更改您的吸气剂:

get
{
    return GetValueOrDefault<_ReturnType>("key");
}

但是,如果此代码分散在多个类中,则必须定义一个包含Properties属性和上述GetValueOrDefault()方法的基类,尽管使用protected而不是{ {1}}。

或者,无论哪种private类型,您都可以将其定义为扩展方法:

Properties

并这样称呼它:

public static T GetValueOrDefault<T>(this IDictionary<string, IMarkerInterface> properties, string key)
{
    IMarkerInterface value = null;
    if (properties != null) properties.TryGetValue(key, out value);
    return value as T;
}

但是,就像@Daniel所说的那样,这闻起来像是一种理想的代码生成方案,因为没有它,您仍然会有几行(复制粘贴,容易出错的)代码。

这些属性应该在何处命名,您可以使用T4模板之类的东西来从中生成此代码文件。

答案 1 :(得分:0)

如果A实现了Properties(例如,像IReadOnlyDictionary<string, object>),那么您可以做的一件事就是添加扩展方法:

Dictionary<string, object>

然后

public static TValue TryGetValue<TValue>(
    this IReadOnlyDictionary<string, object> properties,
    string key)
    where TValue : class
{
    if ((properties != null) &&
         properties.TryGetValue(key, out object value))
    {
        return value as TValue;
    }

    return null;
}

Link to Fiddle

答案 2 :(得分:0)

好吧,你可以这样做:

private IMarkerInterface getIMF(string str) 
{
    IMarkerInterface value = null;
    Properties?.TryGetValue(_string, out value);
    return value;
}

public _ReturnType _PropertyName
    {
      get { return getIMF(_string) as _ReturnType; }
      set { Properties[_string] = value; }
    }
相关问题