【发布时间】:2015-05-11 12:00:19
【问题描述】:
在我的 C# 类中,我想引用类本身的类型,可以吗?
我的示例代码:
在一行
private static List<CRcpParmPropEle<CParam1, string>> ParmPropList;
我不想使用“CParam1”,我希望使用一些通用的方式(比如“this”)来引用自己。因为我有很多像 CParam1 这样的类,所以每个人都需要以这种方式引用自己。
class CParam1
{
private double m_Prop1;
private static List<CRcpParmPropEle<CParam1, string>> ParmPropList;
public CParam1()
{
}
////-> I wish to replace Cparam1 to something like this
public static List<CRcpParmPropEle<CParam1, string>> getParmPropList()
{
if (ParmPropList == null)
{
ParmPropList.Add(new CRcpParmPropEle<CParam1, string>("Prop1", "BA", 0, false));
//-> I wish to replace Cparam1 to something like this
}
return ParmPropList;
}
public string Prop1
{
get
{
return m_Prop1.ToString();
}
set
{
m_Prop1 = -1;
double dW1;
if (double.TryParse(value, out dW1))
{
m_Prop1 = dW1;
}
}
}
public class CRcpParmPropEle<T,TProp>
{
public Func<T, TProp> getter;
public Action<T, TProp> setter;
public string PropName { get; set; }
public string ColPos { get; set; }
public int ColNum { get; set; }
public int RowNum { get; set; }
public bool ReadOnly { get; set; }
public CRcpParmPropEle(string strPropName, string strColPos, int nRowNum, bool bReadOnly)
{
PropName = strPropName;
ColPos = strColPos;
RowNum = nRowNum;
ReadOnly = bReadOnly;
var prop = typeof(T).GetProperty(PropName); //typeof(rcpObj).GetProperty(propName);
getter = (Func<T,TProp>)Delegate.CreateDelegate(typeof(Func<T,TProp>), prop.GetGetMethod());
setter = (Action<T,TProp>)Delegate.CreateDelegate(typeof(Action<T,TProp>), prop.GetSetMethod());
}
}
【问题讨论】:
-
您是否尝试过使用
this.GetType()? -
是否可以选择让您的 CParam1 类型类派生自公共基类或实现公共接口?这将允许您让列表类型引用公共基础或接口,而不是类本身。另外,鉴于此列表已经是静态的,将其放在其他地方怎么样?
-
@slugster,类型名在类的静态属性的类型声明中。
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
-
@DWright 是的,好点,但方法/字段通常是静态的,因为像 Resharper 这样的工具建议它而不是因为它们需要。 IOW 方法/字段是否需要是静态的,这种情况可以参考
this?