Im上的靜態方法調用上使用
我的代碼:
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 + ", ");
}
}
}
}
這幾乎完全一樣,除了靜態展示方法鏈接的例子。
現在在我的主要方法我可以打電話:
GenericClass<int>.Showcase();
我可以改變代碼:
GenericClass<string>.Showcase();
GenericClass<char>.Showcase();
它仍然能工作。
如果我能做到
GenericClass<int> test = new GenericClass<int>();
test.Showcase();
它將使總感覺,我認爲這將需要一個類型,因爲我可以呼籲其他測試方法。
我沒有看到添加類型的優點,需要添加一個隨機類只會導致我腦海中的混亂,爲什麼不是靜態方法的語法genericClass<T>.StaticMethod();
例如將一個類型添加到靜態方法dosnt add anythig(或者是否?)。那麼爲什麼在調用泛型類的靜態方法時需要使用<T>
?
感謝您的補充,您可以添加一個「第二,如果您的方法訪問任何靜態字段會發生什麼?使用泛型類型,每個獨特類型用作類型參數會導致一組新的靜態字段存在。 」。這是迄今爲止我認爲最有意義的論點。 –
@SvenB - 如果您有任何「GenericClass」的實例,並且它訪問一個靜態字段,它將與'GenericClass '的所有其他實例共享該靜態字段。但是這個特定的變量與'GenericClass '可以訪問的不一樣。靜態方法也可以訪問這些相同的字段,但它需要知道通用的「類型」是知道要訪問哪個靜態字段。 –
@SvenB - 我已經在腳註1中添加了一些關於爲什麼你不能使用簡單語法的例子(甚至忽略了其他原因) –