-1

我需要嵌套泛型,如 A< B< Base >> 。

当我这样做时,只有外部属性 (A) 被暴露。我不知道如何访问(B)的方法等。然后我尝试在内部访问接口并获得相同的结果。

(编辑)为了澄清用例,我需要的解决方案应该与 public class C : A < B < Base >> 或 public class C : B < A < Base >> 我不需要那些导致相同的类,但两个定义都有相应的方法。正如您可能怀疑的那样,我正在尝试使用它来以模块化模式跨多个对象实现通用功能。扩展方法让我很接近,但它们不会像这个解决方案那样允许被覆盖的行为(如果可以实现的话)。

我附上了测试代码,它可能比我更清楚地显示问题。

using System;
using System.Reflection;

namespace ArchitecturalTestGround
{
    public interface IBase
    {
        void BaseMethod1();
    }
    public interface IA : IBase
    {
        void AMethod();
    }
    public interface IB : IBase
    {
        void BMethod();
    }
    public class Base : IBase
    {
        public void BaseMethod1() { }
    }
    public class A<T> : IA where T : IBase
    {
        public void BaseMethod1() { }
        public void AMethod() { }
    }
    public class B<T> : IB where T : IBase
    {
        public void BaseMethod1() { }
        public void BMethod() { }
    }
    public class Test1 : A<B<Base>>
    {
    }

    public class Test2 : B<A<Base>>
    {
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            Test1 e1 = new Test1();
            Test2 e2 = new Test2();


            Console.WriteLine("Test1 - A<B<Base>>");
            foreach (MemberInfo mi in typeof(Test1).GetMembers())
            {
                Console.WriteLine($"  {mi.Name}.{mi.MemberType}");
            }
            if (e1 is IB) { Console.WriteLine("   Supports IB"); }
            if (e1 is IA) { Console.WriteLine("   Supports IA"); }

            Console.WriteLine();
            Console.WriteLine("Test2 - B<A<Base>>");
            foreach (MemberInfo mi in typeof(Test2).GetMembers())
            {
                Console.WriteLine($"  {mi.Name}.{mi.MemberType}");
            }
            if (e2 is IB) { Console.WriteLine("   Supports IB"); }
            if (e2 is IA) { Console.WriteLine("   Supports IA"); }

            Console.ReadKey();
        }
    }
}
4

2 回答 2

0

Test1继承自A<T>(不管是什么T)并A<T>继承自 from IA,而后者又继承自IBase,因此您只会看到该继承链中的方法:

来自A<T>

public void BaseMethod1() { }
public void AMethod() { }

来自IA

void AMethod();

来自IBase

void BaseMethod1();

(顺便说一下,从您的代码示例中注意到,由于 BaseMethod1,您可能会收到编译器警告)。

我想我知道你在做什么。您可能遇到过需要从两个类继承的情况。多类继承在 C# 中是不可能的。不过有一些方法可以解决它。

一般来说,如果你遇到这样的情况,往往意味着你需要重新考虑你的设计。如果您仍然对该主题感兴趣,请查看此人:

C#中的多重继承

于 2017-04-28T15:49:12.870 回答
0

是否可以像这样更改您的定义?

public class A<T> : IA where T : IBase
{
    T NestedGeneric;

    public A(T nested)
    {
        NestedGeneric = nested;
    }

    public void BaseMethod1() { }

    public void AMethod() { }
}


public class Test1 : A<B<Base>>
{
    public B<Base> NestedGeneric;
    public Test1(B<Base> nested) : base(nested)
    {
        NestedGeneric = nested;
    }
}

这让你可以做到e1.NestedGeneric.BMethod();

于 2017-04-28T15:52:01.033 回答