c# 如何定义全局变量?

heefan 2011-07-29 11:56:49
我想定义一个单独的文件,用于放置Error Code

类似于C++这样用法,

// filename: errorcode.h
int Err_Bad_File_Name = 100;
int Err_Bad_Person = 101;
// ...


使用时只要include头文件就可以了。

C#是如何处理的?
...全文
2232 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
heefan 2011-07-29
  • 打赏
  • 举报
回复
public int parseFile(string in_filename)
我是要返回值的,如果用enum,我需要显示cast返回值对吧?


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

namespace proj001
{
public enum ErrorCode
{
BAD_INPUT_FILE = 100,
BAD_FILE_EXTENSION
}
}

// in my caller file
public int parseFile(string in_filename)
{
if (in_filename == null)
return (int)ErrorCode.Err_Bad_File_Name; //那就需要cast啦



  • 打赏
  • 举报
回复
用枚举
public enum XXX
threenewbee 2011-07-29
  • 打赏
  • 举报
回复
也可以使用枚举。但是使用常数更方便和其他语言交互,因为C#枚举不能直接转换为整数。
threenewbee 2011-07-29
  • 打赏
  • 举报
回复
对...
heefan 2011-07-29
  • 打赏
  • 举报
回复
那就是这样吧,

// errorcode.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace proj001
{
static class ErrorCode
{
public const int Err_Bad_File_Name = 100;
public const int Err_Bad_Person = 101;
}
}


我的另一个class调用时候,

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

namespace proj001
{
class XPaidUnpaidParser
{
/* ************ Data Member ******************* */
private string m_filename;

/* ************ Member Function *************** */
public int parseFile(string in_filename)
{
if (in_filename == null)
return ErrorCode.Err_Bad_File_Name; //这样调用

m_filename = in_filename;
}
}
}


对吧
threenewbee 2011-07-29
  • 打赏
  • 举报
回复
static class GlobalConstants
{
public const int Err_Bad_File_Name = 100;
public const int Err_Bad_Person = 101;
}
q107770540 2011-07-29
  • 打赏
  • 举报
回复
新建 一个类文件 .cs
存放即可
using 此类文件的命名空间
种草德鲁伊 2011-07-29
  • 打赏
  • 举报
回复
可以用枚举。
种草德鲁伊 2011-07-29
  • 打赏
  • 举报
回复
没全局变量。
fxie8908 2011-07-29
  • 打赏
  • 举报
回复
[Quote=引用 11 楼 fxie8908 的回复:]

首先,你这个变量肯定是在一个公共类里面(C#中方法和成员不能单独存在),比如说是 A,你可以将变量X设置为静态(static),访问符设为public。这样 其他文件里 需要使用此变量,只要将A所在的命名空间引用,然后 A.X即可。
[/Quote]


如果你的Error Code 是固定的,就使用const
fxie8908 2011-07-29
  • 打赏
  • 举报
回复
首先,你这个变量肯定是在一个公共类里面(C#中方法和成员不能单独存在),比如说是 A,你可以将变量X设置为静态(static),访问符设为public。这样 其他文件里 需要使用此变量,只要将A所在的命名空间引用,然后 A.X即可。
种草德鲁伊 2011-07-29
  • 打赏
  • 举报
回复
如果用枚举,那一样也返回枚举类型

public ErrorCode ParseFile(string in_filename)

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧