简体   繁体   English

通用扩展方法,运算符

[英]Generic extension method, operators

I would like to make a method that "transforms" one space to another. 我想提出一种将一个空间“转换”为另一个空间的方法。 This is quite a simple thing to template in C++ but in C# I'm not sure which interface/type or how I need to use the "where" clause in order to get the compiler to understand what I want. 这对于在C ++中进行模板化来说是一件非常简单的事情,但是在C#中,我不确定哪个接口/类型或者我需要如何使用“ where”子句才能使编译器理解我想要的东西。 My C++ function looked like this: 我的C ++函数如下所示:

template<class T>
T Transform(T s, T s1, T s2, T d1, T d2)
{
        T result = (s - s1) / (s2 - s1) * (d2 - d1) + d1;       

        return result;
}   

and my first stab at a generic C# version (in extension methods), looks like this: 和我在通用C#版本(扩展方法中)的第一个步骤看起来像这样:

public static T Transform<T>(T s, T s1, T s2, T d1, T d2)
{
        T result = (s - s1) / (s2 - s1) * (d2 - d1) + d1;       

        return result;
}

Alas C# would like me to be more specific about the types, ie las C#希望我更详细地说明类型,即

"error CS0019: Operator '-' cannot be applied to operands of type 'T' and 'T'". “错误CS0019:运算符'-'不能应用于类型'T'和'T'的操作数”。

What does C# want me to do? C#要我做什么?

You cannot directly tell the compiler via a constraint that T implements a certain operator. 您不能通过约束直接告诉编译器T实现了某个运算符。 You can only tell the compiler that T implements some class. 您只能告诉编译器T实现了某些类。 If this class overloads the operator, then you can use it. 如果此类重载了运算符,则可以使用它。

For example, a class that defines the '-' operator 例如,定义“-”运算符的类

public class Stuff
{
    public Stuff(int number) {
        Number = number;
    }

    public int Number { get; set; }

    public static Stuff operator -(Stuff a, Stuff b) {
        return new Stuff(a.Number - b.Number);
    }

    //Define the other operators in the same way...
}

Then, in your method, you can do this: 然后,在您的方法中,您可以执行以下操作:

public static T Transform<T>(T s, T s1, T s2, T d1, T d2)
    where T : Stuff
{
    Stuff result = (s - s1) / (s2 - s1) * (d2 - d1) + d1;
    return (T)result;
}

Alternatively, you can just use dynamic , but that will throw an exception if the operator does not exist. 或者,您可以只使用dynamic ,但是如果运算符不存在,则会抛出异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM