如何在c#中模仿java'

本文关键字:java | 更新日期: 2023-09-27 18:10:42

我有一个这样的情况:

public class BasicContainer {
}
public class SpecificContainerA : BasicContainer {
}
public class SpecificContainerB : BasicContainer {
}
public class BuilderA<T> where T : BasicContainer 
{
    public bool IsPrimary { ... }
}
public class BuilderB : BuilderA<SpecificContainer>
{
    public bool IsHidden { ... }
}
public class Bar
{
    public Bar Foo(string id, Action<BuilderB> action) {
    }
}

换句话说,我有一个继承了另一个参数化类的类,并固定了这个类型参数。在我的另一个类中,我有一个方法对这个类执行一个操作。

有可能实现这样的事情吗?

public Action<BuilderA<T>> Bla<T>()
    where T : BasicContainer
{
    return c => c.IsPrimary();
}
bar.Foo("id", Bla<SpecificContainerB>());

意思是,我想给我的方法Foo一个更通用的动作作为参数T。

PS:我想我可以这样做:

 public class Bar
 {
    public Bar Foo<T1, T2>(string id, T1 action)
        where T1 : Action<T2>
        where T2 : Container
    {
    }
 }

但是这真的很丑,我希望有更好的东西。你知道吗?

如何在c#中模仿java'

Action<T>是密封的,所以无论如何都不能从它派生。你的类相当于:

 public class Bar
 {
    public Bar Foo<T>(string id, Action<T> action)
        where T : Container
    {
    }
 }

或者,根据你原来的例子:

 public class Bar
 {
    public Bar Foo<T1, T2>(string id, Action<T1> action)
        where T1 : BuilderA<T2>
        where T2 : Container
    {
    }
 }

并且由于编译器可以从传入的动作推断出T的类型,因此不需要指定泛型参数