c# 一次继承 2 类

c# inherit 2 classes at once

我在 C# 4.0 中有一种情况可以从对象的多重继承中获益。

示例:

A​​uthorizeAttribute 和 ApiController 是 MS 标准基础 classes。我想用我写的 class 中的代码扩展每个,这样我就可以执行以下操作:

[AuthorizeAttributeTotalAccess]
public class TemplateController : ApiControllerBase
{
    // ...
}

public class AuthorizeAttributeTotalAccess : AuthorizeAttributeBase
{
    // ...
}

public class AuthorizeAttributeTotalAccess : AuthorizeAttributeBase
{
    protected virtual ClaimsPrincipal CurrentUser
    {
        get { return HttpContext.Current.User as ClaimsPrincipal; }
    }
    protected virtual IEnumerable<dynamic> CurrentUserClaims
    {
        get
        {
            return from c in CurrentUser.Identities.First().Claims
                    select new
                    {
                        c.Type,
                        c.Value
                    };
        }
    }

    // ...
}

public class ApiControllerBase : ApiController
{
    protected virtual ClaimsPrincipal CurrentUser
    {
        get { return HttpContext.Current.User as ClaimsPrincipal; }
    }
    protected virtual IEnumerable<dynamic> CurrentUserClaims
    {
        get
        {
            return from c in CurrentUser.Identities.First().Claims
                    select new
                    {
                        c.Type,
                        c.Value
                    };
        }
    }

    // ...
}

知道如何实现吗?如您所见,两个基础 classes 包含完全相同的代码,但每个基础 class 必须 继承标准 MS classes不同。

这不是完全无缝的,但是对于像这种情况下您想要提供通用辅助方法的情况,您可以选择使用扩展方法。这并不是扩展方法的设计目的,因此不必将调用包装在某些共享 class 中的便利性被其他开发人员在查看您的代码时可能产生的混淆所抵消,并对这些方法的位置感到困惑来自.

public interface IUserHelperMethods
{
    // Empty marker interface
}

public static class UserHelperExtensions
{
    public static ClaimsPrincipal GetCurrentUser(this IUserHelperMethods)
    {
        return HttpContext.Current.User as ClaimsPrincipal;
    }
}

public class ApiControllerBase : ApiController, IUserHelperMethods
{
    public void Foo()
    {
        this.GetCurrentUser();
    }
}

public class AuthorizeAttributeTotalAccess : AuthorizeAttributeBase, IUserHelperMethods
{
    public void Foo()
    {
        this.GetCurrentUser();
    }
}

另请注意,我必须将您的 属性 更改为 Get...() 方法,因为 C# 不支持扩展属性。

在 C# 中无法从两个 class 继承。这与继承自 class 的继承链不同,继承自 class。

不过,如果您查看 C# 规范,将无法解释原因。如果您与团队中的某些人交谈,他们会解释说这与在继承树上重新铸造 class 有关。简而言之,它与绝对的复杂性有关。

This feature is supported in C++.

仅供参考:没有计划将此功能添加到 C#。