确定接口中使用的泛型的数据类型参数
Determine datatype parameter for generic used in interface
我正在努力寻找一种优雅的解决方案来确定在抽象中用作通用参数的接口中的数据类型 class。
摘要class:
public abstract class Entity<T>
{
/// <summary>
/// Object Identifier
/// </summary>
public T Id { get; set; }
}
具体class:
public class Department: Entity<int>
{
// Additional properties
}
public class Employee: Entity<long>
{
// Additional properties
}
接口实现:
public interface IService<T1, T2>
where T1 : Entity<?>
where T2 : Entity<?>
{
Task TransferEmployeeToDepartment(? departmentId, ? employeeId);
}
该问题的解决方案是将数据类型作为附加参数发送,但出于个人和强迫症的原因,我不想这样做。有办法解决吗?
同意丹尼斯的评论。根据您的方法名称,您将具体 class Employee
转换为具体 class Department
。这里没有通用的东西。
所以如果你只想传输这两个实体,你的代码应该是这样的
public class Department: Entity<int>
{
// Additional properties
}
public class Employee: Entity<long>
{
// Additional properties
public Department TransferToDepartment() {} //implementation here
}
如果您的目标是将任何实体转移到任何另一个实体,我会将您的界面重新制作成以下方式
public interface IService<T1, T2>
{
Task TransferEmployeeToDepartment(Entity<T1> entityFrom, Entity<T2> entityTo);
}
但是如果你有一组几乎不相关的实体(比如部门和员工),我怀疑是否有可能为此编写一些好的通用代码
我正在努力寻找一种优雅的解决方案来确定在抽象中用作通用参数的接口中的数据类型 class。
摘要class:
public abstract class Entity<T>
{
/// <summary>
/// Object Identifier
/// </summary>
public T Id { get; set; }
}
具体class:
public class Department: Entity<int>
{
// Additional properties
}
public class Employee: Entity<long>
{
// Additional properties
}
接口实现:
public interface IService<T1, T2>
where T1 : Entity<?>
where T2 : Entity<?>
{
Task TransferEmployeeToDepartment(? departmentId, ? employeeId);
}
该问题的解决方案是将数据类型作为附加参数发送,但出于个人和强迫症的原因,我不想这样做。有办法解决吗?
同意丹尼斯的评论。根据您的方法名称,您将具体 class Employee
转换为具体 class Department
。这里没有通用的东西。
所以如果你只想传输这两个实体,你的代码应该是这样的
public class Department: Entity<int>
{
// Additional properties
}
public class Employee: Entity<long>
{
// Additional properties
public Department TransferToDepartment() {} //implementation here
}
如果您的目标是将任何实体转移到任何另一个实体,我会将您的界面重新制作成以下方式
public interface IService<T1, T2>
{
Task TransferEmployeeToDepartment(Entity<T1> entityFrom, Entity<T2> entityTo);
}
但是如果你有一组几乎不相关的实体(比如部门和员工),我怀疑是否有可能为此编写一些好的通用代码