如何在C#中定义模板成员函数 例如,我将填写任何支持Add(...)成员函数的集合,请查看下面的示例代码
public class CInternalCollection
{
public static void ExternalCollectionTryOne<T<int>>(ref T<int> ext_col, int para_selection = 0)
{
foreach (int int_value in m_int_col)
{
if (int_value > para_selection)
ext_col.Add(int_value);
}
}
public static void ExternalCollectionTryTwo<T>(ref T ext_col, int para_selection = 0)
{
foreach (int int_value in m_int_col)
{
if (int_value > para_selection)
ext_col.Add(int_value);
}
}
static int[] m_int_col = { 0, -1, -3, 5, 7, -8 };
}
ExternalCollectionTryOne&lt; ...&gt;(...)将是首选类型,因为int类型可以显式定义,但会导致错误:
Type parameter declaration must be an identifier not a type
The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)
ExternalCollectionTryTwo&lt; ...&gt;(...)会导致错误:
'T' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)...
我希望问题很清楚 - 有什么建议吗?
----------------------------- edit ----------------- ---------
界面ICollection&lt; ..&gt;的答案没有模板成员工作正常,感谢所有这一点, 但我仍然无法成功定义成员模板(通用)功能
这是一个更简单的例子......我该如何定义
public class CAddCollectionValues
{
public static void AddInt<T>(ref T number, int selection)
{
T new_T = new T(); //this line is just an easy demonstration to get a compile error with type T
foreach (int i_value in m_int_col)
{
if (i_value > selection)
number += i_value; //again the type T cannot be used
}
}
static int[] m_int_col = { 0, -1, -3, 5, 7, -8 };
}
答案 0 :(得分:0)
您可以将其约束为ICollection<T>
。
public static void ExternalCollectionTryTwo<T>(ICollection<T> ext_col, int para_selection = 0)
{
foreach (int int_value in m_int_col)
{
if (int_value > para_selection)
ext_col.Add(int_value);
}
}
但同样,你只是添加int
s。
这应该没关系:
public static void ExternalCollectionTryTwo(ICollection<int> ext_col, int para_selection = 0)
{
foreach (int int_value in m_int_col)
{
if (int_value > para_selection)
ext_col.Add(int_value);
}
}
答案 1 :(得分:0)
回答关于给定的泛型类型,如果我很好理解,你希望有一个除整数以外的其他东西的集合,所以这里是选项:
public class CInternalCollection<T> where T : IComparable
{
private T[] m_T_col;
private CInternalCollection() { }
public CInternalCollection(T[] m_T_col)
{
this.m_T_col = m_T_col;
}
public void ExternalCollection(ICollection<T> ext_col, T para_selection)
{
foreach (T value in m_T_col)
{
if (value.CompareTo(para_selection) > 0)
ext_col.Add(value);
}
}
}
class Program
{
static void Main(string[] args)
{
int[] m_int_col = {0,1,2};
CInternalCollection<int> myCol = new CInternalCollection<int>(m_int_col);
ICollection<int> ext_int_col = new List<int>();
ext_int_col.Add(-1);
ext_int_col.Add(3);
ext_int_col.Add(2);
ext_int_col.Add(5);
myCol.ExternalCollection(ext_int_col, 1);
}
}