根据字符串查找并返回一个类

时间:2013-09-19 10:18:49

标签: c# .net

我有多个类的父类“command_functions”

例如

class Empty_Command : command_functions

每个命令类都覆盖一个值

public override string command_display_name { get { return "Empty"; } }

无论如何都要搜索command_functions的类型,查找command_display_name设置为匹配字符串的位置并返回该字符串。

所以我可以像这样使用它

command_functions find = FindCommand("Empty");
if(find != null)
{
    new find();
}

4 个答案:

答案 0 :(得分:2)

使用泛型可以做到这一点。据我所知,你有一组继承自类Empty_Command的类(我假设是抽象的),你想根据命令名找到要执行的特定类。

我创建了以下示例,该示例假定所有继承的类型都在同一个程序集中。没有问题,如果它们跨越多个组件,只是你的负载不同。

public abstract class Empty_Command
{
    /// <summary>
    /// Find command
    /// </summary>
    /// <param name="commandName">the command name</param>
    /// <returns></returns>
    public static Empty_Command FindCommand(string commandName)
    {
        //get all the types that are inherited from the Empty_Command class and are not abstract (skips empty commad)
        var types = Assembly.GetExecutingAssembly().GetTypes().Where(x => typeof(Empty_Command).IsAssignableFrom(x) && !x.IsAbstract);
        //enuerate all types
        foreach (var type in types)
        {
            //create an instance of empty command from the type
            var item = Activator.CreateInstance(type) as Empty_Command;
            if (item == null)
                continue;
            //test the display name
            if(item.command_display_name.Equals(commandName))
                return item;
        }
        return null;
    }
    public abstract string command_display_name { get; }
}

我评论了一些帮助的代码。但这是我的完整测试存根。

using System;
using System.Linq;
using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var cmd = Empty_Command.FindCommand("command_2");
            if (cmd != null)
                Console.WriteLine(cmd.command_display_name);
            Console.ReadKey();


        }
    }

    public abstract class Empty_Command
    {
        /// <summary>
        /// Find command
        /// </summary>
        /// <param name="commandName">the command name</param>
        /// <returns></returns>
        public static Empty_Command FindCommand(string commandName)
        {
            //get all the types that are inherited from the Empty_Command class and are not abstract (skips empty commad)
            var types = Assembly.GetExecutingAssembly().GetTypes().Where(x => typeof(Empty_Command).IsAssignableFrom(x) && !x.IsAbstract);
            //enuerate all types
            foreach (var type in types)
            {
                //create an instance of empty command from the type
                var item = Activator.CreateInstance(type) as Empty_Command;
                if (item == null)
                    continue;
                //test the display name
                if(item.command_display_name.Equals(commandName))
                    return item;
            }
            return null;
        }
        public abstract string command_display_name { get; }
    }

    public class Command1 : Empty_Command
    {
        public override string command_display_name
        {
            get { return "command_1"; }
        }
    }

    public class Command2 : Empty_Command
    {
        public override string command_display_name
        {
            get { return "command_2"; }
        }
    }

    public class Command3 : Empty_Command
    {
        public override string command_display_name
        {
            get { return "command_3"; }
        }
    }
}

希望这会有所帮助......

答案 1 :(得分:1)

要获取非静态属性的值,需要实例化类型,因此第一个条件是您可以实例化要检查的每个类型。

否则,需要使用反射来获取类型列表,按基类型过滤,实例化并调用属性get方法。

答案 2 :(得分:0)

您正在寻找工厂设计模式。 (http://en.wikipedia.org/wiki/Factory_method_pattern

在此工厂中,您可以创建类似

的功能
command_functions findCommand(string commandText)
{
  if (commandText == "empty") return new Empty_Command();
  if (...) etc
}

答案 3 :(得分:0)

您可以使用以下模式来执行此操作

interface IGroup2
        {
            string SearchOption { get; set; }
            List<Projects> GetProjects();
        }

        public class GroupHead : IGroup2
        {
            public string SearchOption { get; set; }

            public GroupHead()
            {
                SearchOption = "GroupHead";
            }

            public List<Projects> GetProjects()
            {   
                //Code here
                return null;
            }
        }

        public class ProjectIncharge : IGroup2
        {
            public string SearchOption { get; set; }

            public ProjectIncharge()
            {
                SearchOption = "ProjectIncharge";
            }

            public List<Projects> GetProjects()
            {
                //Code here
                return null;
            }
        }

        public class ProjectManager : IGroup2
        {
            public string SearchOption { get; set; }

            public ProjectManager()
            {
                SearchOption = "ProjectManager";
            }

            public List<Projects> GetProjects()
            {
                //Code here
                return null;
            }
        }

public class Test
{
        private static List<IGroup2> searchRuleList = new List<IGroup2>()
        {
          new GroupHead(),
          new ProjectIncharge(),
          new ProjectManager(),
        };

        public static void Main(string[] args)
        {
         IGroup2 searchOptionRule = searchRuleList.Find(delegate(IGroup2 searchRule) { return searchRule.SearchOption.Equals(args[0]); });

        } 
}