【发布时间】:2019-09-05 06:50:42
【问题描述】:
我正在尝试重构我在很多类中使用的方法。举例说明比较简单。
我有这门课:
public class TipoPuntoClaveConst
{
public const int Insercion = 1;
public const int DetectorDePaso = 2;
public const int Sincronizador = 3;
public const int Extraccion = 4;
public static string GetDescripcion(int IdxTipo)
{
var property = typeof(TipoPuntoClaveConst)
.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
.Where(fi => fi.IsLiteral && !fi.IsInitOnly && (int)fi.GetRawConstantValue() == IdxTipo)
.FirstOrDefault();
if (property == null) return string.Empty;
var name = property.Name;
return ResourceHelper.GetTraduccion(ResourceHelper.FICHERO.General, name);
}
}
在项目中,我还有一个用于本地化的 ResourceFile。 GetDescription 方法使用给定值的正确属性名称返回本地化文本。可以看一个使用示例:
<html>
<body>
<select id="cbTipo">
<option value="@TipoPuntoClaveConst.Insercion">@TipoPuntoClaveConst.GetDescripcion(TipoPuntoClaveConst.Insercion)</option>
...
</select>
</body>
</html>
问题是,我必须在我的所有 const 类中复制粘贴该方法。我正在尝试在基类中实现此方法,例如:
public class TipoPuntoClaveConst : ConstMaster {...}
public class ConstMaster {
public static string GetDescripcion(int IdxTipo)
{
var property = typeof(TipoPuntoClaveConst)
.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
.Where(fi => fi.IsLiteral && !fi.IsInitOnly && (int)fi.GetRawConstantValue() == IdxTipo)
.FirstOrDefault();
if (property == null) return string.Empty;
var name = property.Name;
return ResourceHelper.GetTraduccion(ResourceHelper.FICHERO.General, name);
}
}
但我不知道如何将var property = typeof(TipoPuntoClaveConst) 替换为更通用的东西,例如var property = typeof(¿this?)
【问题讨论】:
-
你为什么不
Type myType = this.GetType()? -
因为
GetDescripcion是静态方法 -
如果你没有声明方法静态并且在基类中你
this.GetType()在一个方法中,当实例化一个子/继承类并在子实例中调用该方法时,你会得到正确的类型(孩子/继承的)。 -
@bradbury9 我知道,但我不想删除
static如果你看一下我们的例子,我并没有声明一个对象来调用该方法,所以,通过删除它我将不得不检查我的所有代码以纠正我所有的 const 类。 -
您希望它是静态的,但不想实例化,好的,刚刚编辑了我的答案。