首页 > 解决方案 > 带有泛型类型参数的 C# 构造函数与接口相结合

问题描述

好的,我们开始吧!我尝试做以前从未尝试过的事情,然后…… C# 咬了我一口。

问题是我的程序需要将一些输入对象转换为输出对象,同时多进一出。并且 out 需要 in 进行实例化。

我不确定我在这一点上是否很清楚......所以一个例子来说明这一点会更好:

public class Class1
{
    public interface ITranslatable { }

    public interface ITranslatable<T> { }

    public class OriginClass : ITranslatable { }

    public class TargetClass : ITranslatable<OriginClass>
    {
        public TargetClass(OriginClass origin)
        {
            // Instantiate some properties from arg
        }
    }

    public class Test
    {
        public Y Execute<X, Y>(X origin, Y target)
            where X : ITranslatable
            where Y : ITranslatable<X>, new()
        {
            target = new Y(origin); // <= How can I make this
            // Some stuff
            return target;
        }
    }

    public TargetClass Function(OriginClass origin, TargetClass target)
    {
        var test = new Test();
        return test.Execute(origin, target);
    }
}

标签: c#genericsinterface

解决方案


您声明了 new() 约束,这意味着您希望类具有 empy 无参数构造函数。

下面的代码符合您的需要吗?

 public class Class1
{
    public interface ITranslatable { }

    public interface ITranslatable<T>
    {
        T Origin { get; set; }
    }

    public class OriginClass : ITranslatable
    {

    }

    public class TargetClass : ITranslatable<OriginClass>
    {
        private OriginClass _origin;

        public OriginClass Origin
        {
            get => _origin;
            set
            {
                //Do some stuff
                _origin = value;
            }
        }

        public TargetClass()
        {

        }

    }

    public class Test
    {
        public Y Execute<X, Y>(X origin, Y target)
            where X : ITranslatable
            where Y : ITranslatable<X>, new()
        {
            var result = new Y {Origin = origin};

            // Some stuff
            return target;
        }
    }

    public TargetClass Function(OriginClass origin, TargetClass target)
    {
        var test = new Test();
        return test.Execute(origin, target);
    }
}

推荐阅读