泛型和算术问题C# [英] Generics and the arithmetic problem C#

查看:50
本文介绍了泛型和算术问题C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,以下代码是我尝试在C#中创建一个泛型类。

的想法是创建一个相同类型的元素数组

问题我遇到的是当试图计算数组中元素的总和时,c#中的泛型类不允许我做算术

任何帮助请



hello everyone the following code is my attempt to create a generic class in C#
the idea is to create an Array of elements of the same type
the problem i ran into is when try trying to calculate the sum of the element in an array , generic classes in c# doesn't allow me to do arithmetics
any help please

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Devoire
{
    class Tableau<T>
    {
        private T[] tab;
        int cnt;

        public Tableau(int ss = 0)
        {
            tab = new T[ss];
            cnt = 0;
        }
        public Tableau(T[] ar, int count)
        {
            if (count > ar.Length)
                count = ar.Length;
            tab = new T[count];
            for (int i = 0; i < count; i++)
            {
                if (ar[i] != null)
                {
                    tab[i] = ar[i];
                    cnt++;
                }
            }
            
        }

        public T this[int index]
        {
            get {
                if( index < cnt)
                {
                    return tab[index];
                }
                else
                {
                    return default(T);
                }
            }
            set
            {

                    if (index >= cnt)
                    {
                        index = cnt++;
                    }
                    if (cnt > tab.Length)
                    {
                        T[] newtab = new T[cnt];
                        Array.Copy(tab, newtab, index);
                        tab = newtab;
                    }

                    tab[index] = value;

            }
        }
        public  static Tableau<T>   fusionner(Tableau<T> tabl, Tableau<T> tab2)
        {
            Tableau<T> tmp = new Tableau<T>(tabl.cnt + tab2.cnt);
            for(int i = 0 ; i < tabl.cnt ; i++)
            {
                tmp[i] = tabl[i];
            }
            for (int i = tabl.cnt , j = 0 ; i < tmp.taille; i++)
            {
                tmp[i] = tab2[j++];
            }
            return tmp;
            
        }
        public int taille
        {
            get
            {
                return tab.Length;
            }
        }
        public T Premier
        {
            get
            {
                return tab[0];
            }
            set
            {
                tab[0] = value;
                if (cnt == 0)
                    cnt++;
                             
            }
        }
        public override string ToString()
        {
            string s = "" ;
            for (int i = 0 ;  i < cnt ; i++)
            {

                s += tab[i] + " ";
            }
            return s;
        }
        public  Tableau<T> copie(Tableau<T> tabl)
        {
            cnt = tabl.cnt;
            tab = new T[cnt];
            for (int i = 0; i <cnt; i++ )
            {
                tab[i] = tabl[i];
            }
            return this;
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
           
            double[] ar = { 1.2, 125.3, 3.3, 4, 10.3, 11, 12 };
            int[] ar1 = { 1, 125, 3, 4, 10, 11, 12 };
            int a = ar.Length;
            Tableau<double> tb = new Tableau<double>(ar,3);
            Tableau<int> tb2 = new Tableau<int>(ar1, 4);

            Tableau<int> tb3 = new Tableau<int>(15);
            tb3.Premier = 6;
            tb3.Premier = tb3.Premier *  (int)tb.Premier;
            Console.WriteLine(tb3);
        }
    }
}





我尝试了什么:



i在线寻找解决方案,但我不了解大部分解决方案

任何帮助都会很棒

谢谢



What I have tried:

i search for a solution online but i didn't understand most of them
any help would great
thank you

推荐答案

事实上,正如解决方案2中所解释的那样,这是一个有趣的问题。不幸的是,它没有一个完美的解决方案。

请看我过去的答案:

C#中的泛型:编译时错误,'+'无法应用 [ ^ ],

方法的一般约束 [ ^ ]。



另请参阅我对解决方案2的评论。



-SA
Indeed, as it is explained in Solution 2, is an interesting problem. Unfortunately, it does not have a perfect solution.
Please see my past answer:
Generics in C#: compile-time error, '+' cannot be applied[^],
Generic constraints on methods[^].

See also my comment to Solution 2.

—SA


泛型不能算术,因为并非所有类都支持所需的所有操作。例如,虽然您可以减去两个DateTime值以获得Timespan,但是通过将它们添加到一起,您将获得什么? :笑:

因为并非所有可能成为泛型的目标的类都支持运算符,所以如果没有明确地转换它们,就不能在任何泛型类型上使用它们。

例外情况是当您对通用类型使用约束时:

Generics can't do arithmetic because not all classes support all the operations required. For example, while you can subtract two DateTime values to get a Timespan, what on earth would you get by adding them together? :laugh:
Because not all possible classes that could be the "target" of the generic support the operators, you can't use them on any generic type without explicitly casting them.
The exception is when you use a constraint on the type of the generic:
private class myClass<T> where T : baseClass
    {

但是......在这种情况下你不能使用任何约束,如int,double和所以是结构,而不是类,因此是隐式密封的 - 类型约束必须是可导出的类。



对不起 - 但你不能做你想要的通过泛型!

But...you can't use any constraint in this case, as int, double and so forth are structs, not classes and as such are implicitly sealed - a type constraint must be a derivable class.

Sorry - but you can't do what you want via generics!


有趣的问题。



因为并非所有类型都支持算术,并且在.NET中没有通用的运算符支持必须将特定于类型的运算符注入您的通用Tableau类。



要添加对添加的支持,您可以向您的通用类添加委托变量,例如:

Interesting question.

Since not all types support arithmetics and there is no generic operator support in .NET you must inject a type-specific operator into your generic Tableau class.

To add support for addition you can add a delegate variable to your generic class like this
public static Func<t,t,t> Addition;



然后您可以从这样的Sum函数调用


which you then can invoke from a Sum function like this

public T Sum()
{
    T sum = default(T);
    for (int i = 0; i < cnt; i++)
    {
       sum = Addition(sum, tab[i]);
    }
    return sum;
} 



在使用此方法之前,您必须通过简单地分配添加功能一次教该类如何添加您想要使用的类型


Before using this method you must "teach" the class how to add the types you want to use by simply assigning the Addition function once

Tableau<int>.Addition = (a,b) => a+b;
Tableau<string>.Addition = (a,b) => a+b;</string></int>


每个
你想要使用的类型。



我认为这个想法可以推广(并通过一些封装改进)。如果有人发现它有用,我可以在这里的文章中提出。


for each type that you want to use.

I think this idea can be generalized (and improved by some encapsulation). If anyone finds it useful I may present in an article here.


这篇关于泛型和算术问题C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆