C# 缩短几乎相同属性的语法
我不得不修改一些代码,偶然发现了几个类,它们定义了大量非常相似的属性 它们看起来像这样:C# 缩短几乎相同属性的语法,c#,properties,C#,Properties,我不得不修改一些代码,偶然发现了几个类,它们定义了大量非常相似的属性 它们看起来像这样: private T GetValueOrDefault<T>(string key) { IMarkerInterface value = null; if (Properties != null) Properties.TryGetValue(key, out value); return value as T; } public _ReturnType _Prope
private T GetValueOrDefault<T>(string key)
{
IMarkerInterface value = null;
if (Properties != null) Properties.TryGetValue(key, out value);
return value as T;
}
public _ReturnType _PropertyName
{
收到
{
IMarkerInterface值=空;
如果属性!=null Properties.TryGetValue_字符串,则输出值;
返回值为_ReturnType;
}
设置{Properties[_string]=value;}
}
它们之间唯一的区别是_ReturnType,字典属性中使用的_字符串,显然还有_PropertyName
我想知道是否有办法缩短语法?如果您看到重复的代码,您将提取一个方法。它看起来像这样:
private T GetValueOrDefault<T>(string key)
{
IMarkerInterface value = null;
if (Properties != null) Properties.TryGetValue(key, out value);
return value as T;
}
并称之为:
get
{
return Properties.GetValueOrDefault<_ReturnType>("key");
}
但是,正如@Daniel评论的那样,这闻起来像是生成代码的理想场景,因为如果没有它,您仍然会有几行复制粘贴的、容易出错的代码
这些属性的名称可能有一个来源,您可以使用T4 templates之类的工具从中生成此代码文件。如果属性实现IReadOnlyDictionary(例如字典),您可以做的一件事是添加扩展方法:
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;
}
然后
public IMarkerInterface MarkerInterface
{
get => Properties.TryGetValue<IMarkerInterface>("MarkerInterface");
set { Properties["MarkerInterface"] = value; }
}
你可以这样做:
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; }
}
使用代码生成工具。因此,您只希望缩短语法或同时或主要减少代码重复?请就以下问题提问:
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; }
}