What are some good alternatives to multiple-inheritance in .NET?

后端 未结 6 1434
梦如初夏
梦如初夏 2020-12-13 13:49

I\'ve run into a bit of a problem with my class hierarchy, in a WPF application. It\'s one of those issues where you have two inheritance trees merging together, and you can

6条回答
  •  星月不相逢
    2020-12-13 14:13

    One approach is to use extension methods with an interface to provide your "derived class" implementation, much like System.Linq.Queryable:

    interface ICustomizableObject
    {
        string SomeProperty { get; }
    }
    
    public static class CustomizableObject
    {
        public static string GetXamlHeader(this ICustomizableObject obj)
        {
            return DoSomethingWith(obj.SomeProperty);
        }
    
        // etc
    }
    
    public class CustomizableControl : System.Windows.Controls.UserControl, ICustomizableObject
    {
        public string SomeProperty { get { return "Whatever"; } }
    }
    

    Usage: As long as you have a using directive for (or are in the same namespace as) the namespace where your extension methods are defined:

    var cc = new CustomizableControl();
    var header = cc.GetXamlHeader();
    

提交回复
热议问题