方法在函数在程序中运行之前返回值调用



我试图理解C#4.5中的泛型数据类型,我创建了类检查,其中带有返回类型bool的简单方法CompareMyValue比较两个值。现在在我的主类中,我创建对象并用输入参数调用这个方法,但我在调试过程中意识到,主类调用中的方法不会为bool a1和a2返回正确的结果。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace C_Sharp_Practice_Code_01.GenericCollection
{
class check<UNKNOWNDATATYPE>
 {
    public bool CompareMyValue(UNKNOWNDATATYPE x, UNKNOWNDATATYPE y)
    {
        if(x.Equals(y))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
  } 
}

主舱

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using C_Sharp_Practice_Code_01.GenericCollection;
namespace C_Sharp_Practice_Code_01
{
 class mainClass
 {
    static void Main(string[] args)
    {
        mainClass obj1 = new mainClass();
        obj1.call_GenericClass();
    }
    public void call_GenericClass()
    {
        check<int> _check = new check<int>();
        check<string> _check2 = new check<string>();
        bool a1 = _check.CompareMyValue(1, 1);
        bool a2 = _check2.CompareMyValue("xyz", "xyz");
    }
 }
}

main类调用中的方法没有为bool返回正确的结果a1和a2。

也许您在调用CompareMyValue函数之前检查了行上的布尔变量?


我在一个示例项目中测试了你的代码,它对我来说很好:

bool a1 = _check.CompareMyValue(1, 1); 
System.Diagnostics.Debug.Print(a1.ToString()); // prints true
bool a2 = _check2.CompareMyValue("xyz", "xyz");
System.Diagnostics.Debug.Print(a2.ToString()); // prints true
bool a3 = _check2.CompareMyValue("x", "y"); // another example
System.Diagnostics.Debug.Print(a3.ToString()); // prints false

我设法让它工作。。。

class check<T>
{
    public bool CompareMyValue(T x, T y)
    {
        if (x.Equals(y))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

然后用测试

check<int> intChecker = new check<int>();
Console.WriteLine(intChecker.CompareMyValue(4, 5).ToString());
Console.ReadKey();
check<string> strChecker = new check<string>();
Console.WriteLine(strChecker.CompareMyValue("The test", "The test").ToString());
Console.ReadKey();
check<decimal> decChecker = new check<decimal>();
Console.WriteLine(decChecker.CompareMyValue(1.23456m, 1.23456m).ToString());
Console.ReadKey();
check<DateTime> dateChecker = new check<DateTime>();
Console.WriteLine(dateChecker.CompareMyValue(new DateTime(2013, 12, 25), new DateTime(2013, 12, 24)).ToString());
Console.ReadKey();

最新更新