简体   繁体   English

有没有办法从 C# 中的多个类中提取公共接口

[英]Is there a way to extract a common interface from multiple classes in C#

I've got some code generated from an XSD, one of the properties is an array that can be one of 7 different classes, all these classes share some fields so I would like to create an interface so I can iterate over the array and access the 'tpl' property without having to do a huge switch statement and casting.我有一些从 XSD 生成的代码,其中一个属性是一个可以是 7 个不同类之一的数组,所有这些类共享一些字段,所以我想创建一个接口,以便我可以遍历数组并访问'tpl' 属性,而无需执行巨大的 switch 语句和强制转换。

I've done this manually for now just for the 'tpl' property but I was wondering if there was a tool or way to paste all the classes into something and it would identify the common properties and generate an interface for me?我现在只是为'tpl'属性手动完成了这项工作,但我想知道是否有一种工具或方法可以将所有类粘贴到某个东西中,它会识别公共属性并为我生成一个接口?

My Google fu is only comming up with things that will extract an interface from a single class or keep a class and interface in sync.我的谷歌 fu 只提出了从单个 class 中提取接口或保持 class 和接口同步的东西。

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("DT", typeof(DT2))]
        [System.Xml.Serialization.XmlElementAttribute("IP", typeof(IP2))]
        [System.Xml.Serialization.XmlElementAttribute("OPDT", typeof(OPDT2))]
        [System.Xml.Serialization.XmlElementAttribute("OPIP", typeof(OPIP2))]
        [System.Xml.Serialization.XmlElementAttribute("OPOR", typeof(OPOR2))]
        [System.Xml.Serialization.XmlElementAttribute("OR", typeof(OR2))]
        [System.Xml.Serialization.XmlElementAttribute("PP", typeof(PP2))]
        public object[] Items {
            get {
                return this.itemsField;
            }
            set {
                this.itemsField = value;
            }
        }

Well I managed to write this myself, wasn't too hard after all.好吧,我设法自己写了这个,毕竟不是太难。

Created a new Console App, added my other project as a reference.创建了一个新的控制台应用程序,添加了我的其他项目作为参考。 Add each Class to the list of lists then intersect each list with the previous to remove any items that don't exist in all Classes.将每个 Class 添加到列表列表中,然后将每个列表与前一个列表相交以删除所有类中不存在的任何项目。

It's a bit rough and could be extended to public methods, and possibly a filter on the reflection to make sure the properties are actually public as well.它有点粗糙,可以扩展到公共方法,并且可能是反射过滤器以确保属性实际上也是公共的。

Would welcome any comments on how to improve it.欢迎对如何改进它提出任何意见。

var listOfLists = new List<List<Properties>>();

listOfLists.Add(GetPropertyList<Class1>());
listOfLists.Add(GetPropertyList<Class2>());
listOfLists.Add(GetPropertyList<Class3>());


var output = Intersect(listOfLists);
WriteInterfaceOut(output);


static List<Properties>? Intersect(List<List<Properties>> listOfLists)
{
    List<Properties>? outputList = null;
    foreach (var item in listOfLists)
    {
        if (outputList == null)
        {
            outputList = item;
            continue;
        }

        outputList = outputList.Intersect(item, new Properties.Comparer()).ToList();
    }
    return outputList;
}

static void WriteInterfaceOut(List<Properties>? list)
{
    Console.WriteLine("public interface IRenameMe \r\n{");
    foreach (var item in list)
    {
        Console.WriteLine($"    public {item.TypeName} {item.Name} {{get; set;}}");
    }
    Console.WriteLine("}");
    Console.ReadKey();

}

static List<Properties> GetPropertyList<T>()
{
    var list = new List<Properties>();
    PropertyInfo[] myPropertyInfo;

    myPropertyInfo = typeof(T).GetProperties();
    for (int i = 0; i < myPropertyInfo.Length; i++)
    {
        list.Add(new Properties() { Name = myPropertyInfo[i].Name, TypeName = myPropertyInfo[i].PropertyType });
    }   
    return list;
}

public class Properties
{
    public string Name { get; set; }
    public Type TypeName { get; set; }


    public class Comparer : IEqualityComparer<Properties>
    {
        public bool Equals(Properties? x, Properties? y)
        {
            return x?.Name == y?.Name && x?.TypeName == y?.TypeName;
        }

        public int GetHashCode([DisallowNull] Properties obj)
        {
            unchecked
            {
                var hash = 17;
                hash = hash * 23 + obj.Name.GetHashCode();
                hash = hash * 23 + obj.TypeName.GetHashCode();
                return hash;
            }
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 向从 C# 接口继承的类添加通用方法? - Add common method to classes inheriting from a C# Interface? 实现通用接口的类中的C#协方差 - C# Covariance in Classes Implementing Common Interface 多个类的C#接口 - C# Interface for multiple classes 强类型属性引用多个类,没有通用接口(C#) - Strongly-typed property reference to multiple classes with no common interface (C#) 通过通用接口包装C#类以与多态性一起使用 - Wrapping C# classes to use with polymorphism through a common interface 寻找一种从通用源代码生成Java和C#类的方法 - Looking for a way to generate Java and C# classes from common source code 在C#中的多个类中使用相同的命名空间是常见的做法 - Is it common practice to use the same Namespace in multiple classes in C# 有没有办法像C#一样从Visual Studio 2008的VB中的类中提取接口代码? - Is there a way I can extract an interface code from a class in VB on visual studio 2008 like C# does? 有没有办法在C#的多个类中使用变量? - Is there a way to use a variable in multiple classes in C#? 在 C# Autofac 中,如何从具有多个具体类的单个接口解析类 - In C# Autofac, how to resolve class from single interface with multiple concrete classes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM