关于C# 加法的问题,想写一个方法,这个方法既可以执行double类型的相加,也可以执行int类型的相加等等

keaidepangzi 2019-05-24 04:27:21
不知如何编程,好像要用到泛型还是什么别的知识,自己实在写不出来,谢谢
...全文
385 16 打赏 收藏 转发到动态 举报
写回复
用AI写文章
16 条回复
切换为时间正序
请发表友善的回复…
发表回复
jx315425246 2019-06-02
  • 打赏
  • 举报
回复
基本概念,叫重载,基本操作叫效率 我就两个字符串 “1” + “2” =“12” 吗?
泡泡龙 2019-05-31
  • 打赏
  • 举报
回复
C#是强类型语言,你只能用泛型或者装箱来实现这玩意
得鹿梦鱼、 2019-05-31
  • 打赏
  • 举报
回复

Console.WriteLine(Get_Add(double.Parse("1.23"), double.Parse("2.32")));
Console.WriteLine(Get_Add(int.Parse("1"), int.Parse("2")));
Console.WriteLine(Get_Add("1","2")); 
public dynamic Get_Add(dynamic d , dynamic a)
{
     return a + d;
}
像这种可以执行double,int,float,string的加法
华芸智森 2019-05-31
  • 打赏
  • 举报
回复
'//十几年前从一本NET的书上抄一来的,一直用到现在. 例如: MsgBox("1+2+3/5*pi+log(e)+max(1,2,3,4,5,6)".Evaluate)


#Region "字符串表达式计算"

    Const Num As String = "(\-?\d+\.?\d*)"
    Const Func1 As String = "(exp|log|log10|abs|sqr|sqrt|sin|cos|tan|asin|acos|atan|atan|round|tanh|truncate|floor|ceiling)"
    Const Func2 As String = "(atan2)"
    Const FuncN As String = "(min|max)"
    Const Constants As String = "(e|pi)"

    Private rePower As New Regex(String.Concat(Num, "\s*(\^)\s*", Num))
    Private reAddSub As New Regex(String.Concat(Num, "\s*([-+])\s*", Num))
    Private reMulDiv As New Regex(String.Concat(Num, "\s*([*/])\s*", Num))
    Private reFunc1 As New Regex(String.Concat(Func1, "\(\s*", Num, "\s*\)"), RegexOptions.IgnoreCase)
    Private reFunc2 As New Regex(String.Concat(Func2, "\(\s*", Num, "\s*,\s*", Num, "\s*\)"), RegexOptions.IgnoreCase)
    Private reFuncN As New Regex(String.Concat(FuncN, "\((\s*", Num, "\s*,)+\s*", Num, "\s*\)"), RegexOptions.IgnoreCase)
    Private reSign1 As New Regex("([-+/*^])\s*\+")
    Private reSign2 As New Regex("\-\s*\-")
    Private rePar As New Regex("(?<![A-Za-z0-9])\(\s*([-+]?\d+.?\d*)\s*\)")
    Private reNum As New Regex("^\s*[-+]?\d+\.?\d*\s*$")
    Private reConst As New Regex(String.Concat("\s*", Constants, "\s*"), RegexOptions.IgnoreCase)

    ''' <summary>
    ''' 字符串表达式计算.如:pi*(100+23)*1.2/35
    ''' 注:这个函数使用的是正则,所以速度是呵呵的,只能在前台界面.
    ''' (exp|log|log10|abs|sqr|sqrt|sin|cos|tan|asin|acos|atan|atan|round|tanh|truncate|floor|ceiling)
    ''' (atan2)
    ''' (min|max)
    ''' (e|pi)
    ''' 支持 括号,四则运算,EXP,LOG,LOG10,SQR,SQRT,三角函数.MIN,MAX,e,pi 
    ''' ** 注:还没有测试线程安全,所以,先不要用在服务器上。
    ''' </summary>
    ''' <param name="expr"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    <Extension()> Public Function Evaluate(ByVal expr As String) As Double

        If String.IsNullOrWhiteSpace(expr) Then Return 0

        expr = reConst.Replace(expr, AddressOf DoConstants)

        Do Until reNum.IsMatch(expr)
            Dim saveExpr As String = expr

            Do While rePower.IsMatch(expr)
                expr = rePower.Replace(expr, AddressOf DoPower)
            Loop

            Do While reMulDiv.IsMatch(expr)
                expr = reMulDiv.Replace(expr, AddressOf DoMulDiv)
            Loop

            Do While reFuncN.IsMatch(expr)
                expr = reFuncN.Replace(expr, AddressOf DoFuncN)
            Loop

            Do While reFunc2.IsMatch(expr)
                expr = reFunc2.Replace(expr, AddressOf DoFunc2)
            Loop

            Do While reFunc1.IsMatch(expr)
                expr = reFunc1.Replace(expr, AddressOf DoFunc1)
            Loop

            expr = reSign1.Replace(expr, "$1")
            expr = reSign2.Replace(expr, "+")

            Do While reAddSub.IsMatch(expr)
                expr = reAddSub.Replace(expr, AddressOf DoAddSub)
            Loop

            expr = rePar.Replace(expr, "$1")

            '//表达式错误
            If expr = saveExpr Then
                '//Throw New SyntaxErrorException()
                Return 0
            End If
        Loop

        Return Val(expr)

    End Function

    Friend Function DoConstants(ByVal m As Match) As String
        Dim V As String = String.Empty
        Select Case m.Groups(1).Value.ToUpper
            Case "PI"
                V = Math.PI.ToString
            Case "E"
                V = Math.E.ToString
        End Select
        Return V
    End Function

    Friend Function DoPower(ByVal m As Match) As String
        Dim n1 As Double = Val(m.Groups(1).Value)
        Dim n2 As Double = Val(m.Groups(3).Value)
        Return (n1 ^ n2).ToString
    End Function

    Friend Function DoMulDiv(ByVal m As Match) As String
        Dim n1 As Double = Val(m.Groups(1).Value)
        Dim n2 As Double = Val(m.Groups(3).Value)
        Dim V As String = String.Empty
        Select Case m.Groups(2).Value
            Case "/"
                V = (n1 / n2).ToString
            Case "*"
                V = (n1 * n2).ToString
        End Select
        Return V

    End Function

    Friend Function DoAddSub(ByVal m As Match) As String

        Dim n1 As Double = Val(m.Groups(1).Value)
        Dim n2 As Double = Val(m.Groups(3).Value)
        Dim V As String = String.Empty

        Select Case m.Groups(2).Value
            Case "+"
                V = (n1 + n2).ToString
            Case "-"
                V = (n1 - n2).ToString
        End Select

        Return V

    End Function

    Friend Function DoFunc1(ByVal m As Match) As String
        Dim V As String = String.Empty
        Dim n1 As Double = Val(m.Groups(2).Value)
        Select Case m.Groups(1).Value.ToUpper
            Case "EXP"
                V = Math.Exp(n1).ToString
            Case "LOG"
                V = Math.Log(n1).ToString
            Case "LOG10"
                V = Math.Log10(n1).ToString
            Case "ABS"
                V = Math.Abs(n1).ToString
            Case "SQR", "SQRT"
                V = Math.Sqrt(n1).ToString
            Case "SIN"
                V = Math.Sin(n1).ToString
            Case "COS"
                V = Math.Cos(n1).ToString
            Case "TAN"
                V = Math.Tan(n1).ToString
            Case "ASIN"
                V = Math.Asin(n1).ToString
            Case "ACOS"
                V = Math.Acos(n1).ToString
            Case "ATAN"
                V = Math.Atan(n1).ToString
            Case "ROUND"
                V = Math.Round(n1).ToString
            Case "TANH"
                V = Math.Tanh(n1).ToString
            Case "Truncate".ToUpper
                V = Math.Truncate(n1).ToString
            Case "Floor".ToUpper
                V = Math.Floor(n1).ToString
            Case "Ceiling".ToUpper
                V = Math.Ceiling(n1).ToString
        End Select
        Return V
    End Function

    Friend Function DoFunc2(ByVal m As Match) As String
        Dim V As String = String.Empty
        Dim n1 As Double = Val(m.Groups(2).Value)
        Dim n2 As Double = Val(m.Groups(3).Value)
        Select Case m.Groups(1).Value.ToUpper
            Case "ATAN2"
                V = Math.Atan2(n1, n2).ToString
        End Select

        Return V

    End Function

    Friend Function DoFuncN(ByVal m As Match) As String

        Dim V As String = String.Empty
        Dim args As New ArrayList()
        Dim i As Integer = 2
        Do While m.Groups(i).Value <> String.Empty
            args.Add(StrToDec(m.Groups(i).Value.Replace(","c, " "c)))
            i += 1
        Loop

        Select Case m.Groups(1).Value.ToUpper
            Case "MIN"
                args.Sort()
                V = args(0).ToString
            Case "MAX"
                args.Sort()
                V = args(args.Count - 1).ToString
        End Select

        Return V

    End Function

#End Region
jx315425246 2019-05-25
  • 打赏
  • 举报
回复

public string Add(int a,int b)
{
return (a+b).ToString();
}

public string Add(int a,float b)
{
return ((float)a+b).ToString();
}

........


改参数类型就可以
  • 打赏
  • 举报
回复
这个是重载问题吧 还好没想 INT+double private string abc(obj a boj b) { return (a+b).tostring(); //可以实现 int、 double 、 int +double 和 double+int }
jx315425246 2019-05-24
  • 打赏
  • 举报
回复
写同函数名,返回值不同,参数不同,这叫重载
keaidepangzi 2019-05-24
  • 打赏
  • 举报
回复
能进行,就是想用一个方法,调用这个方法,既可以用double类型的a,b,又可以用int的a,b作为参数进行相加运算
wid999 2019-05-24
  • 打赏
  • 举报
回复
要方法的话,直接并列写,编译器直接认为是重载。
        double Add(double op1, double op2) { return op1 + op2; }
int Add(int op1, int op2) { return op1 + op2; }
wid999 2019-05-24
  • 打赏
  • 举报
回复
弱弱地问下,“+”不能计算这两种类型?
bloodish 2019-05-24
  • 打赏
  • 举报
回复
需求比较奇怪。。。

        public T Add<T>(T t1, T t2) 
        {
            if(typeof(T).IsPrimitive 
                && typeof(T) != typeof(bool)
                && typeof(T) != typeof(char))
            {
                dynamic d1 = t1;
                dynamic d2 = t2;
                return (d1 + d2);
            }
            else
            {
                return default;
            }
        }
正怒月神 2019-05-24
  • 打赏
  • 举报
回复
你直接 都是转 Decmial类型算了。 别搞这么复杂。
stherix 2019-05-24
  • 打赏
  • 举报
回复
最简单的就是方法重载 想要一个方法做到的,都会很别扭
Hi-Jimmy 2019-05-24
  • 打赏
  • 举报
回复
      
public string Add<T>(T a, T b) where T:struct
{
if (typeof(T) == typeof(int))
{
return (int.Parse(a + "") + int.Parse(b + "")).ToString();
}
else if (typeof(T) == typeof(double))
{
return (double.Parse(a + "") + double.Parse(b + "")).ToString();
}
//float,long.....

return default(T).ToString();
}
  • 打赏
  • 举报
回复
写错了跑到C++去了!

template <class 形参>
形参 相加(形参 a, 形参b){ return a + b; }
  • 打赏
  • 举报
回复

template <class 形参>
void 相加(形参 A, 形参 B){return A+B;}

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧