2013-04-18 76 views
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<>)。只有这样我才能从Base<>的静态Create方法中返回Derived<,>

可能吗?

+1

这感觉就像一个天生的设计缺陷,因为包括循环依赖(A的B继承,而B的需求了解A)。为什么工厂方法不能进入派生类? –

+1

你能否提供一些关于*为什么*你有这些要求的背景?派生类本身是否需要可见? –

+1

@ T.Kiley我同意这是非标准的,但实质上不是'Encoding.UTF8'等等的行为? (虽然可能不是他们如何在内部实现) –

回答

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 
} 
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 
    { 

    } 
} 
+0

哦,不,我知道内在。正在寻找答案我的确切问题 – nawfal

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> 
{ 

} 

现在这个工程..

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() 
    { 

    } 
} 
+0

致命的反思?呐;)在我的情况下不需要。这不是一个死或死的情况.. – nawfal