繁体   English   中英

映射类C#

[英]Mapping classes c#

尝试使用xustom标头进行一些映射

如果template是一个类,并且每个模板可能具有不同的转换,那么为什么不只在您的模板类中包含transform函数呢?

public static myentrypoint( ITemplate t);
{
   t.transform();
}

我处理此类情况的方法是使用泛型 博客文章的无耻自我提升

基本上,您将像这样设置您的基类:

public abstract class Transformer<T>
    where T : Template
{
    public abstract void Transform(T item);
}

然后,您可以为每种类型派生如下:

public class Transformer1 : Tansformer<Template1>
{
    public void Transform(Template1 item) 
    {

    }
}

public class Transformer2 : Transformer<Template2>
{
    public void Transform(Template2 item)
    {

    }
}

然后,您只需要一个工厂即可为您提供正确的Transformer

public class TransformFactory
{
    public Transformer<T> GetTransformer<T>(T item)
    {
        if (item is Template1)
            return new Transformer1();
        else if (item is Template2)
            return new Transformer2();
        // ...
    }
}

这种方法的好处是,您将能够在具体的实现中封装该特定类型的所有行为。 如果它们上都有任何共同的行为,则可以在抽象的基础上进行。

在C#中基于参数的方法(不带switch-case语句)

OOP中 ,基于[ 打开 / 关闭 原理 ]的说法,即诸如类和函数之类的软件实体应打开以进行扩展,而关闭以进行修改。

使用switch-case语句的方法会对此原理提出质疑。 为了在代码内实现这一原理而又不引起其功能的改变。

我们使用一个名为“ Delegate Dictionary Pattern”的模式

例如,我们有一个名为Template的实体,该实体保留输入值以及一些用于处理此Template的Transform类。


保持输入值的模板

public class Template
{
    public int TransformNo { get; set; }
    public string Title { get; set; }
}

ITransform接口用于转换摘要

public interface ITransform
{
    void Do(Template template);
}

将Transform1作为ITransform的具体类

public class Transform1 : ITransform
{
    public void Do(Template template)
    {
        Console.WriteLine($"Transform : {template.TransformNo}, TemplateTitle : { template.Title}");
    }
}

将Transform2作为ITransform的具体类

public class Transform2 : ITransform
{
    public void Do(Template template)
    {
        Console.WriteLine($"Transform : {template.TransformNo}, TemplateTitle : { template.Title}");
    }
}

用于* ITransformer **协调模板的TransformCordinator

public class TransformCordinator
{
    Dictionary<int, Action<Template>> transformMap = new Dictionary<int, Action<Template>>();
    public TransformCordinator()
    {
        transformMap.Add(1, x => new Transform1().Do(x));
        transformMap.Add(2, x => new Transform2().Do(x));
    }

    public void Do(Template template)
    {
        transformMap[template.TransformNo](template);
    }
}

//示例

 class Program
  {
    static void Main(string[] args)
    {

        var transformCordinator = new TransformCordinator();
        transformCordinator.Do(new Template() { TransformNo = 1, Title = "Hi!" });

        Console.ReadLine();
    }
}

暂无
暂无

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

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