c# - C# 中模板类型的必需属性

标签 c# generics

考虑通用方法,是否可以对模板类型设置约束以具有某些特定属性?

为了编译成功以下代码为例

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/

相关文章:

c# - 如何发送og :Title og:Image og:Description og:url info from C# to Facebook

C# 泛型接口(interface)协变

c# - 如何将 'Convert' 类包装到通用函数中

c# - 从通用类型实例调用 ToString 覆盖

c# - 过滤数据集

c# - Form.ShowDialog() 并处理

c# - 如何防止 slider 拉伸(stretch)?

c# - Web API 请求后需要记录 EF DbContext 的 CaSTLe Windsor 生活方式

java - 使用泛型执行强制转换时发出警告

swift - 如何在 Swift 中使用具有关联类型的协议(protocol)作为返回值?