无法从另一个类中调用静态方法 [英] Unable to call static method in class from another
问题描述
我有一个类文件,其中包含一个散列输入字符串的函数.
使用系统;使用 System.Security.Cryptography;使用 System.Linq;使用 System.Text;使用 System.Threading.Tasks;命名空间 XHD_Console{公共类哈希系统{公共静态字符串 Sha256(字符串文本){string hashString = string.Empty;//这里的散列代码,包含一些我不想发布的东西.返回哈希字符串;}}}
我想从表单中调用 sha256 函数,intellisense 检测到类 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();}
您需要针对 class
调用 static
成员,而不是针对 实例class
的 em>.所以你需要使用:
HashingSystem.sha256("textthere");
另外,考虑改变:
class HashingSystem
到:
公共类HashingSystem
类是内部
默认情况下.我建议您始终明确可见性(即始终指定internal
、public
或private
).>
I have a class file which contains a function to hash an input string.
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;
}
}
}
I want to call the sha256 function from a form, intellisense detects the class HashingSystem, but not the function. Is there a reason? I've read it needs to be static, done that but to no avail. Both classes are in the same namespace, but the class hashingsystem has it's own file, hashingsystem.cs
To call the function:
private void submit_Click(object sender, EventArgs e){
this.EnteredPassword = HashingSystem.sha256(input_Password.Text);
this.DialogResult = DialogResult.OK;
this.Close();
}
You need to call static
members against the class
, not against an instance of a class
. So you need to use:
HashingSystem.sha256("texthere");
Also, consider changing:
class HashingSystem
to:
public class HashingSystem
Classes are internal
by default. I would recommend you always be explicit about visibility (i.e. always specify internal
, public
or private
).
这篇关于无法从另一个类中调用静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!