考虑通用方法,是否可以对模板类型设置约束以具有某些特定属性?
为了编译成功以下代码为例
public static int[] DoSomething<T> (T[] Input)
{
int[] Output = new int[Input.Length];
for (int i = 0;i < Input.Length;i++)
Output[i] = (int)Input[i].PropertyA+(int)Input[i].PropertyB;
return Output;
}
模板类型需要实现PropertyA和PropertyB。 是否可以以某种方式对模板类型设置这样的约束?
编辑: 另外还要求 PropertyA 和 PropertyB 为数字类型,以便它们可以输入为 int。
谢谢。
最佳答案
唯一的可能性是将 T 定义为从某个众所周知的基类派生的类型或实现众所周知的接口(interface):
public interface IWellKnown
{
int PropertyA { get; }
int PropertyB { get; }
}
您的任何方法都是:
public static int[] DoSomething<T> (T[] Input) where T : IWellKnown
{
int[] Output = new int[Input.Length];
for (int i = 0;i < Input.Length;i++)
Output[i] = Input[i].PropertyA+Input[i].PropertyB;
return Output;
}
编辑:
创建适用于任何数字类型但仅适用于数字类型的通用方法是不可能的,因为 .NET 没有像 Number
这样的任何基本类型。因此,您不能将泛型类型仅限于数字。所有数字类型都是值类型,因此您可以执行以下操作:
public interface IWellKnown<TData> where TData : struct
{
TData PropertyA { get; }
TData PropertyB { get; }
}
但在这种情况下,您的界面将接受任何值类型 - 任何自定义结构、char、bool 等。
关于c# - C# 中模板类型的必需属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5926747/