我跟随这个通用类的例子。因为我不想用测试代码填充项目的主要功能,所以我想创建一个静态展示函数来运行代码示例。
我的代码:
namespace Syntax
{
public class GenericClass<T>
{
private class Node
{
private T data;
private Node next;
public Node(T t)
{
next = null;
data = t;
}
public Node Next { get { return next; } set { next = value; } }
public T Data { get { return data; } set { data = value; } }
}
private Node head;
public GenericClass()
{
head = null;
}
public void AddHead(T t)
{
Node n = new Node(t);
n.Next = head;
head = n;
}
public IEnumerator<T> GetEnumerator()
{
Node current = head;
while (current != null)
{
yield return current.Data;
current = current.Next;
}
}
public static void Showcase()
{
GenericClass<int> list = new GenericClass<int>();
for(int x = 0; x <10; x++)
{
list.AddHead(x);
}
System.Console.WriteLine("\nPrinting generic class using ints.");
foreach (int i in list)
{
System.Console.Write(i + ", ");
}
GenericClass<char> listChars = new GenericClass<char>();
string abc = "abcdefghijklmnopqrstuvw";
foreach (char c in abc)
{
listChars.AddHead(c);
}
System.Console.WriteLine("\n\nPrinting generic class using chars.");
foreach (var c in listChars)
{
System.Console.Write(c + ", ");
}
}
}
}
除了静态Showcase方法外,它与链接的示例几乎完全相同。
现在,在我的主要方法中,我可以调用:
GenericClass<int>.Showcase();
我可以使用以下方式更改代码:
GenericClass<string>.Showcase();
GenericClass<char>.Showcase();
而且仍然可以。
如果我能做
GenericClass<int> test = new GenericClass<int>();
test.Showcase();
对我来说,它将需要一个类型,就像我可以在测试中调用其他方法一样。
我看不到添加类型的优势,添加随机类的需求只会导致我的困惑,为什么静态方法的语法不是genericClass<T>.StaticMethod();
例如在静态方法中添加类型的方法dosnt add anythig(或这样做) ?)。那么,为什么<T>
在泛型类上调用静态方法时需要使用?
由于尚未创建名为的类GenericClass
,因此已创建了名为的开放通用类GenericClass<T>
。
没有什么可以阻止您GenericClass
在同一名称空间中创建类,也没有什么可以阻止您也创建名为的类GenericClass<T1,T2>
。所有这些都可以存在于相同的名称空间中,除非您声明一个,否则它们之间没有显式或隐式关系。
因此,如果要在“在一个类型参数中通用的GenericClass类”上调用静态方法,则必须以某种方式说出这一点,并且已经找到了实现方法-通过提供类型参数。
有人可能会争辩说,如果静态方法不使用type参数,那么它是多余的-那么为什么不能仅使用仍然打开的type参数来调用它呢?好吧,首先,因为那必须是新语法才能允许这种情况发生1。其次,如果您的方法访问任何静态字段会怎样?对于泛型类型,用作类型参数的每个唯一类型都会导致存在一组新的静态字段。
为什么不是静态方法的语法
genericClass<T>.StaticMethod();
例如...
上面的内容是在我最初的回答之后添加的,我希望已经在下面的脚注1中解决了这一问题。但是如果不清楚,这种简单的语法将无法工作。您需要发明一些新的语法,因为您可能具有:
class Abc<T> {
void DoSomething(){
GenericClass<T>.StaticMethod();
}
}
要么
namespace X {
class T {
}
class Abc {
void DoSomething(){
GenericClass<T>.StaticMethod();
}
}
}
在以上两个示例T
中,外部范围已经定义了它们。因此,您需要使用其他方式说“我不想为该泛型的第一个类型参数提供类型”。
1如 能够说GenericClass<T>.Showcase
。任何允许它的新语法都不可能如此简单。因为a)T
调用上下文中范围内可能有一个泛型类型参数,或者b)通用类型参数的名称可能与调用上下文中范围内的其他类型名称冲突。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句