2014-11-04 34 views
2

所以我對C#編程還比較陌生,所以我確信我在這裏犯了一個非常簡單的錯誤。我正在使用Visual Studio製作控制檯應用程序,並且在此應用程序中,我正在嘗試查找數字的平方根。我有.NET框架。
這裏是我的程序的頂部:C#Math.Sqrt()不起作用

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

namespace Linear 
{ 
    public static class Math 
    { 
     static void Main() 
     { 
      // program in here 
     } 
    } 
} 

在節目中,我有一條線,是這樣的:

double distanceA = Math.Sqrt(totalA); 

所以,當我建立程序與VS,它告訴我, 'Linear.Math'不包含'Sqrt'的定義。 爲什麼這麼說?我如何給它定義'Sqrt'?

+2

** TL; DR **'System.Math.Sqrt(totalA);' – Cyral 2014-11-04 02:40:45

回答

24

因爲你命名你的Math類,Visual Studio和編譯器不知道你指的是你自己的類(Linear.Math),或.NET Math類(System.Math)。

您可以指定你想通過改爲由完全限定名稱:

double distanceA = System.Math.Sqrt(totalA); 

這指定你想使用System.Math使用.NETMath類。您可以通過將下面的使用指令後使用在整個文件:

using Math = System.Math; 

這就是所謂的using alias directive,這將告訴MathSystem.Math編譯器。

請注意,創建自己的類時通常不建議使用衝突的名稱。

+0

謝謝!這工作完美! – 2014-11-04 02:43:20

+2

@ColeZ。如果此答案解決了您的問題,請將其標記爲解決方案。 – MichaelS 2014-11-04 08:32:02