【发布时间】:2012-08-27 20:57:23
【问题描述】:
在写这篇文章时,我正在检查与相关主题相关的所有问题 并且无法找到这个 Newbs C# 问题的简单答案
我想......如果可以的话,尽可能多地给出一个解释清楚的答案(拜托!)
我做了一个公共静态类
public static class MyLoadedBtmpToolBox
{
public static string FnameToLoad;
public static bool PutLoadedByteArrInPicbox;
public static string[] LoadedRefrnce;
public static int SourceX_Loaded, SourceY_Loaded, RectWidth_Loaded, RectHeight_Loaded;
---> public static int tst = Str2Int(LoadedRef[0]);
public static byte[] LoadedByteArr;
}
默认情况下,这个类在我使用的主要表单中
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.IO;
using System.Security.Cryptography;
using WindowsInput;
namespace MyScrCupTry1
{
public partial class MyForm1 : Form
{
public static class MyLoadedBtmpToolBox
{
public static int testStr2Int = Str2Int("100");
}
public int Str2Int(string STR)
{
int strInt = Convert.ToInt32(null);
if (isntEmpty(STR))
{
strInt = Convert.ToInt32(STR);
}
else
{
MessageBox.Show("theString " + STR + " is Null");
}
return strInt;
}
}
我无法使用主窗体中的公共“辅助方法”Str2Int() 来为 testStr2Int 赋值
我遇到错误:
错误 1 非静态字段、方法或属性需要对象引用 'MyScrCupTry1.MyForm1.Str2Int(string)' G:\RobDevI5- Raid-0\Documents\Visual Studio 2010\Projects\WindowsFormsApplication2\WindowsFormsApplication2\MyForm1.cs 95 45 MyScrCuptry1
从静态类访问主窗体公共元素的正确方法是什么 如果可能/(不违法)...
- 重新编辑
在这两个答案之后...
我试图实现 第一个答案的代码没有预期的结果我想我不知道正确的代码结构与覆盖 OnLoad(..) 的东西......
但是!
我已将方法 Str2Int(STR) 从 public 变成 public static
所以现在表单本身的元素仍然可以访问(我很惊讶)Str2Int()
并且从静态类中我也可以访问它......
感谢 tp 也将其设为静态,
当将 Str2Int() 从 public 更改为 public static 时,我是否缺少其他“隐藏”缺点?
【问题讨论】:
标签: c# class static-classes