c# - 带有泛型类型参数的 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);
}
}
解决方案
您声明了 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);
}
}
推荐阅读
- api - 我正在尝试从 Companies House API 获取 pdf 文档
- javascript - 为什么我收到此警告 159:35 警告预计将在箭头函数数组回调返回的末尾返回一个值?
- python - 在 Pony ORM 查询中使用枚举
- snowflake-cloud-data-platform - Snowflake JDBC 驱动程序内部错误:无法检索第一个箭头块的行数:null -- 仅发生在 SELECT 语句上
- behat - 更新到 Drupal 8.9.15 时,我在 Probo 上收到以下 Behat JS 错误。不知道这意味着什么。想法?
- javascript - 使用条件更新对象中的特定值
- python - 为什么 if 语句中的“或”运算符不起作用?
- excel - 这些条不会在我的 Excel 图表中排列是否有原因?
- javascript - 如何为 React Bootstrap 表单自动设置高度
- wpf - ObservabaleCollection 添加/删除不会更新 xaml 端的 ItemsControl