【问题标题】:Unable to call static method in class from another无法从另一个类中调用静态方法
【发布时间】:2017-08-24 11:08:01
【问题描述】:

我有一个类文件,其中包含一个散列输入字符串的函数。

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 函数,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();
}

【问题讨论】:

  • 它只是一个普通的windows C#表单,用于输入密码,因此是哈希函数。
  • 使 HashingSystem 成为公共类
  • 如果它们确实在同一个命名空间和项目中,它们是否是内部权限无关紧要。
  • OP 最有可能创建一个 HashingSystem 实例,而不是静态调用它

标签: c# winforms


【解决方案1】:

您需要针对class 调用static 成员,而不是针对class实例。所以你需要使用:

HashingSystem.sha256("texthere");

另外,考虑改变:

class HashingSystem

到:

public class HashingSystem

类默认为internal我建议您始终明确说明可见性(即始终指定 internalpublicprivate)。

【讨论】:

  • 它是公共静态类,但是像HashingSystem.sha256(string) 这样调用它会给我一个错误;当前上下文中不存在名称“sha256”
  • 请更新您的帖子以包含调用代码的整个方法,以及实际的HashingSystem类(因为您帖子中的HashingSystem类绝对是公开)。还请附上您收到的编译器错误的屏幕截图。
  • 有一类 HashingSystem。我尝试过公开课程,但没有成功。
【解决方案2】:

你想这样做吗?

    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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 2013-10-18
    • 2010-12-24
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    相关资源
    最近更新 更多