1
public class Base<S>
{
    public static Derived<S, T> Create<T>()
    {
        return new Derived<S, T>(); //if not public, I wont get it here.
    }
}

public class Derived<S, T> : Base<S>
{
    public Derived() //the problem, dont want it public
    {

    }
}

这是我得到的基本结构。

要求:

1)我根本不希望Derived<,>构造调用Derived<,>类的实例,无论是通过构造函数还是静态方法。我希望它只能通过Base<>. 所以这就出来了:

public class Derived<S, T> : Base<S>
{
    Derived()
    {

    }

    public static Derived<S, T> Create()
    {
        return new Derived<S, T>();
    }
}

2)Derived<,>类本身必须是公共的(这意味着我不能私有嵌套Derived<,>在里面Base<>)。只有这样我才能Derived<,>Create.Base<>

可能吗?

4

4 回答 4

3

您可以制作派生类的构造函数internal,如

public class Base<S>
{
    public static Derived<S, T> Create<T>()  // visible externally
    {
        return new Derived<S, T>(); 
    }
}

public class Derived<S, T> : Base<S>
{
    internal Derived() // not visible outside the current assembly
    {

    }
}
于 2013-04-18T21:33:38.327 回答
1

反射!

void Main()
{
    Derived dr = Base.GetDerived<Derived>();
}

public class Base
{
    public int ID { get; set; }
    public Base()
    {

    }

    public static T GetDerived<T>() where T : Base
    {
        T toReturn = (T)typeof(T).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null).Invoke(null);
        return toReturn;
    }

}

public class Derived : Base
{
    private Derived()
    {

    }
}
于 2013-04-18T21:46:03.677 回答
0

我通过这种方式实现了我的要求:

public abstract class Base<S>
{
    public static Derived<S, T> Create<T>() 
    {
        return new ReallyDerived<S, T>(); 
    }



    class ReallyDerived<T> : Derived<S, T>
    {
        public ReallyDerived()
        {

        }
    }
}

public abstract class Derived<S, T> : Base<S>
{

}

现在这有效..

于 2013-04-18T21:41:33.777 回答
0

我会声明一个公共接口,并将实现设为私有Base

public class Base<S>
{
    public static IFoo<S, T> Create<T>()
    {
        return new Derived<T>(); //if not public, I wont get it here.
    }

    // Only generic in T, as we can use S from the containing class
    private class Derived<T> : Base<S>, IFoo<S, T>
    {
        public Derived()
        {
            ...
        }
    }
}

public interface IFoo<S, T>
{
    // Whatever members you want
}
于 2013-04-18T22:24:30.973 回答