내 사용자 지정 스택 클래스로 작업 중이며 새 스택 (일반 개체)을 만들기위한 일반 메서드를 만들려고합니다. 나는 int 유형의 스택을 많이 사용하고 가끔 다른 유형이 필요합니다. T의 defult 유형을 int로 설정할 수 있습니까?
방법은 다음과 같습니다.
public static Stack<T> newStack<T>(int length)
{
Stack<T> s = new Stack<T>();
for (int i = 0; i < length; i++)
{
Console.WriteLine("print num");
string input = Console.ReadLine();
T value = (T)Convert.ChangeType(input, typeof(T));
s.Push(value);
}
return s;
}
다음과 같은 방법을 사용하고 싶습니다.
newStack(5);//defult int type
다른 유형의 경우
newStack<string>(5)
아무도 도울 수 있습니까? 감사.
T에 대한 기본 유형을 지정할 수는 없지만 newStack
원하는 동작을 얻기 위해 단순히 메서드를 오버로드 할 수 있습니다 . 오버로드 된 메서드는 유형의 새 스택을 자동으로 만듭니다 int
.
코드는 다음과 같습니다.
public static Stack<T> newStack<T>(int length)
{
Stack<T> s = new Stack<T>();
for (int i = 0; i < length; i++)
{
Console.WriteLine("print num");
string input = Console.ReadLine();
T value = (T)Convert.ChangeType(input, typeof(T));
s.Push(value);
}
return s;
}
public static Stack<int> newStack(int length)
{
// Call our original new stack method but pass
// integer as the type T
return newStack<int>(length);
}
이제 다음과 같이 정수 유형의 새 스택을 생성하려는 경우 두 번째 메서드를 호출 할 수 있습니다.
newStack(5);
그렇지 않으면 다음을 사용하여 다른 유형의 스택을 만들 수 있습니다.
newStack<string>(5);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다