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

C# C中模板类型中的必需属性#,c#,generics,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

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

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

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;
}
公共静态int[]DoSomething(T[]输入)
{
int[]输出=新的int[Input.Length];
for(int i=0;i
模板类型需要实现PropertyA和PropertyB。 是否可以对模板类型设置这样的约束

编辑: 此外,还要求PropertyA和PropertyB是数字类型,以便可以将它们键入int


谢谢。

唯一的可能性是将T定义为派生自某个已知基类或实现已知接口的类型:

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;
}

但在这种情况下,您的接口将接受任何值类型—任何自定义结构、char、bool等。

不可能创建这样的限制。您应该在运行时检查输入,并抛出一条有用的异常错误消息

但是,您可以执行以下操作:

public interface IWellKnown<TData> where TData : struct
{
    TData PropertyA { get; }
    TData PropertyB { get; }
}
public interface IWellKnown
{
   int PropertyA { get; }
   int PropertyB { get; }
}

public abstract class WellKnownBase<T> : IWellKnown
{
   IWellKnown.PropertyA { get { return Convert(this.PropertyA); } }
   IWellKnown.PropertyB { get { return Convert(this.PropertyB); } }

   public T PropertyA { get; }
   public T PropertyA { get; }

   protected virtual int Convert(T input) { return (int)input; }
}
将为您提供一个浮动类。如果类型不可强制转换为int,则可以提供自定义转换器:

public class WellKnownTimeSpan : WellKnownBase<TimeSpan>
{
    protected override int Convert(TimeSpan input) 
    { 
        return (int)input.TotalMilliseconds; 
    }
}
公共类WellKnownTimeSpan:WellKnownBase
{
受保护的覆盖整数转换(时间跨度输入)
{ 
返回(int)input.total毫秒;
}
}
顺便说一下,使用linq并将需求添加到接口中,您可以将函数重写为
input.Select(x=>x.PropertyA+x.PropertyB)).ToArray()


PS:请使用VisualStudio检查代码,我只是在没有编译器支持的情况下写出来;)可能会有一些小的编译时错误。

是的,你是对的,但是如果我要求这些属性通常是数字,而不一定是整数,该怎么办呢。对不起,我把问题弄错了。不过还是谢谢你的回答。
public class WellKnownTimeSpan : WellKnownBase<TimeSpan>
{
    protected override int Convert(TimeSpan input) 
    { 
        return (int)input.TotalMilliseconds; 
    }
}