我有这个C#WinForms代码,其中我有几个不同的structs
,所有功能以相同的方式。所以,我试图使用模板来代替编写单独的函数来添加或删除项目。如何从模板调用方法?
例如,这里是一个struct
和相应的List<>
我使用存储其objects
:
public struct Alias
{
public string alias;
public string aliasSource;
public static bool IsValid(...); //This function exists in all the structs
};
List<Alias> aliases;
这从外部使用,添加别名功能:
public void AddAlias(Alias iAlias)
{
AddGenericStructItem<Alias>(iAlias, aliases);
}
这是实际添加的功能:
private void AddGenericStructItem<T>(T genericStructItem, List<T> genericList)
{
string outputError;
if (T.IsValid(genericStructItem, out outputError)) //< -- Problem in the 'T' being used in the far left
{
if (genericList.Contains(genericStructItem))
{
MessageBox.Show("ERROR 82ha5jb :: Item already exists");
}
else
{
genericList.Add(genericStructItem);
}
}
else
{
MessageBox.Show(outputError);
}
}
问题发生在T.IsValid...
部分。编译器给我的T
以下错误:
'T' is a 'type parameter', which is not valid in the given context
有没有解决这个办法吗?我所有的structs
都有一个IsValid
函数,它们具有相同的设置,所以如果我不在这里使用模板,反复编写相同的代码似乎很愚蠢......
C#泛型与C++中的模板明显不同,尽管语法看起来很相似。 –
我感兴趣的是为什么IsValid()是静态的。我希望称为IsValid()的方法需要访问该对象。 – itsme86
是的,这是一种看待它的方式,我猜。我使用它的方式是当我需要验证输入本身时(基于哪个结构实例在以后创建),所以验证需要事先发生,这就是为什么在这种情况下需要静态方法。 – Ahmad