2017-08-24 106 views
-3

我有一個類文件,其中包含一個函數來散列輸入字符串。無法從另一個類調用靜態方法

using System; 
using System.Security.Cryptography; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace XHD_Console 
{ 
    public class HashingSystem 
    { 
     public static string Sha256(string text) 
     { 
      string hashString = string.Empty; 
      //code for hashing here, contains some things i'd rather not release. 
      return hashString; 
     } 
    } 
} 

我想從形式調用SHA256功能,智能檢測類HashingSystem,但不是功能。有理由嗎?我讀過它需要是靜態的,做到了,但無濟於事。這兩個類都在同一個命名空間,但該類hashingsystem有它自己的文件,hashingsystem.cs

調用的函數:

private void submit_Click(object sender, EventArgs e){ 
    this.EnteredPassword = HashingSystem.sha256(input_Password.Text); 
    this.DialogResult = DialogResult.OK; 
    this.Close(); 
} 
+0

這只是一個普通的Windows C#的形式,這對密碼輸入,從而散列函數。 –

+1

使HashingSystem成爲公共類 –

+0

如果兩個類不在同一個Assembly(編譯單元/ Visual Studio項目)中,則將HashingSystem公開。 –

回答

4

你需要調用static成員對class,而不是針對實例class。所以,你需要使用:

HashingSystem.sha256("texthere"); 

此外,考慮改變:

class HashingSystem 

到:

public class HashingSystem 

類是internal默認。 我建議你始終明確可見度(即始終指定internal,publicprivate)。

+0

它是公共靜態類,但將其稱爲「HashingSystem.sha256(string)」給我一個錯誤;名稱'sha256'在當前上下文中不存在 –

+0

請更新您的文章以包含調用代碼**的整個**方法以及實際的HashingSystem類(因爲您的文章中的HashingSystem類絕對是**不**公開)。還請包括您收到的編譯器錯誤的屏幕截圖。 – mjwills

+0

有一個類哈希系統。我曾試圖讓公開課沒有工作。 –

3

你想要做這個嗎?

HashingSystem hs = new HashingSystem(); 
    hs.sha256("Hello World"); //This wont work as static methods cannot be called via instances 

使用以下方式代替

HashingSystem.sha256("Hello world");//Calling directly via class