Development Tip

퀴즈로 C #의 중첩 된 제네릭 클래스 이해

yourdevel 2020. 12. 5. 10:46
반응형

퀴즈로 C #의 중첩 된 제네릭 클래스 이해


동료와 C #에 대해 이야기하면서 그는 출력을 예측해야하는 C # 코드를 보여주었습니다. 처음에는 단순 해 보였지만 그렇지 않았습니다. 나는 C #이 왜 이런 식으로 작동하는지 정말로 이해할 수 없습니다.

코드:

public class A<T1>
{
    public T1 a;

    public class B<T2> : A<T2>
    {
        public T1 b;

        public class C<T3> : B<T3>
        {
            public T1 c;
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        A<int>.B<char>.C<bool> o = new A<int>.B<char>.C<bool>();

        Console.WriteLine(o.a.GetType());
        Console.WriteLine(o.b.GetType());
        Console.WriteLine(o.c.GetType());

        Console.ReadKey();
    }
}

출력은 다음과 같습니다.

System.Boolean
System.Char
System.Int32

내가 틀렸다면 정정하십시오.하지만 에서 상속 하고 상속 o.a하기 때문에 bool 유형 이라는 것을 이해합니다 . 그리고 나는 또한 약간 그 이해 의 유형 때문에 int 유형의 IS 는 외부 클래스에서 얻는다 (나는 생각한다).C<T3>B<T3>B<T2>A<T2>o.ccT1

o.bchar 유형 인지 알아 내려고 할 때 내 머리가 거의 폭발 합니다. 누군가 나에게 이것을 설명 할 수 있습니까?


이것은 오래된 퍼즐이며 매우 어렵습니다. 내가 Anders 자신에게 그것을 줬을 때 그는 처음에 올바른 답을 얻지 못했습니다!

동료가 제공 한 버전은 Cyrus의 블로그에서 가져온 것입니다.

http://blogs.msdn.com/b/cyrusn/archive/2005/08/01/446431.aspx

내 블로그에 약간 더 간단한 버전이 있습니다.

http://blogs.msdn.com/b/ericlippert/archive/2007/07/27/an-inheritance-puzzle-part-one.aspx

내 버전에 대한 해결책은 다음과 같습니다.

http://blogs.msdn.com/b/ericlippert/archive/2007/07/30/an-inheritance-puzzle-part-two.aspx

간단히 말해서, 혼란스러운 동작의 이유는 외부 클래스와 기본 클래스 모두에 존재하는 이름이있을 때 기본 클래스가 "승리"하기 때문입니다. 즉, 다음이있는 경우 :

public class B
{
  public class X {}
} 
public class P
{
  public class X
  {
    public class D : B
    {
      public class N : X {}
    }
  }
}

Then P.X.D.N inherits from B.X, not from P.X. The puzzle makes nested generic types in such a way that the same declaration can be named via both the "outer" and "base" search paths, but has different meanings in each because of generic construction.

Anyway, read the explanation on the blog posts, and if its still not clear, ask a more specific question.


Ok, my first answer was wrong. The nesting is important:

in o.b.GetType() b is the member of the surrounding class which is instantiated as B<char> which inherits from A<char> which in turn makes T1 equal to char. What's not quite clear is the following (manual instantiation for A_int.B_char.C_bool):

public class A_bool
{
    public bool a;

    public class B_bool : A_bool
    {
        public bool b;
    }
}

public class A_char
{
    public char a;

    public class B_bool : A_bool
    {
        public char b;
    }
}

public class A_int
{
    public int a;

    public class B_char : A_char
    {
        public int b;

        public class C_bool : A_char.B_bool
        {
            public int c;
        }
    }
}

Here C_bool could have been derived from A_bool.B_bool as well, right? But since we're nested in A_char that's preferred.

참고URL : https://stackoverflow.com/questions/14237621/understanding-nested-generic-classes-in-c-sharp-with-quiz

반응형