简体   繁体   English

选择和实例化C#类的正确方法取决于字符串值?

[英]Right way to choose and instantiate C# class depends on string value?

I have base class 我有基础课

public abstract class HostBehavior : SiteHost
{
    public abstract List<string> ParseNews(string url);
}

And many derived classes... 还有许多派生类...

What is the best way to choose which constructor should be called depends on url? 选择哪种构造方法最好的最佳方法是取决于url?

Right now I have long sequence of "if else" statements like this example: 现在,我有很长的“ if else”语句序列,例如以下示例:

public static HostBehavior ResolveHost(string url)
{
    if (uri.IndexOf("stackoverflow.com") > 0)
    {
        return new stackoverflowBehavior();
    }
    else if(uri.IndexOf("google.com") > 0)
    {
        return new googleBehavior();
    }
    // and so on...
    else
    {
        throw new Exception...
    }
}

I decided to give each class a custom attribute 我决定给每个班级一个自定义属性

[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct)]
public class HostAttribute : System.Attribute
{
    public string name;

    public HostAttribute(string name)
    {
        this.name = name;
    }
}

So my classes looks like 所以我的课程看起来像

[Host("stackoverflow.com")]
public class stackoverflowBehavior : HostBehavior
{
//...
}

Now I can get all classes from assembly's folder|namespace 现在我可以从程序集的folder | namespace中获取所有类

Assembly asm = Assembly.GetExecutingAssembly();
Type[] hostTypes = asm.GetTypes()
            .Where(a => a.IsClass && a.Namespace != null && a.Namespace.Contains(@"Hosts"))
            .ToArray();

Finally I need to find type with HostAttribute same as incoming url.Host 最后,我需要找到与传入URL相同的HostAttribute类型

foreach(Type t in hostTypes)
{
     HostAttribute attribute = (HostAttribute)Attribute.GetCustomAttribute(t, typeof(HostAttribute));
     if (attribute.name ==  url.Host)
         return (HostBehavior)Activator.CreateInstance(t);
}

I want to thank everyone quotes, especially to Ed Plunkett. 我要感谢每个人的名言,尤其是对埃德·普伦凯特的致辞。

查看您在查询中解释的方案,看来您可以使用工厂模式来满足您的要求。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM