c#里的get和set访问器,不写和只写get+set有区别吗?

get和set访问器可以提供验证功能,也可以设置属性的只读,有很多功能。但是,很多属性只写get和set,没有方法体,例如:
public int BufferSize { get; set; }
这样的话跟不写get和set,即
public int BufferSize;
有什么区别啊?反正是都能读写,也没什么其它附加功能。请大神指教,实在是想不明白。。。

c#

2个回答

一个是字段,一个是属性,字段和属性的概念你应该知道吧

u011574838
a516117636 知道,说说具体的有什么区别啊,用法上,我觉得一样
大约 3 年之前 回复

首先从两者的声明上来看,公共字段只是类用public修饰符所公开的简单公共变量,而属性则是对字段的封装,它使用get和set访问器来控制如何设置或返回字段值。

由于属性的实质是方法(get或set方法),在IL中是没有属性的概念的。所以对于开发过程中常用的赋值和取值操作来说,使用公共变量肯定会比使用属性速度要快,性能上也稍高(方法和变量哪个速度不用说了吧)。

公共字段虽然在速度上快,但它必须开放字段为public,这样一来对象的调用者便可以直接修改其值,值的内容是否合法,运行中是否会出错,就没有了保障,进而会大大降低类的可重用性;相反,属性类似于方法,它可以对存入的变量的值进行处理,如果觉得该值不合法,可以就地变换或者直接提出警告。这对该类的对象的使用安全有很大好处,在运行过程中,因公共变量值的错误而产生的问题会大大减少。

从上述内容来看,两者各有优缺点,在实际项目开发过程中,我们究竟选择使用哪一种方式呢?

如果满足下面几个条件,那么我们便可以大胆地使用公共字段:

1. 允许自由读写;

2. 取值范围只受数据类型约束而无其他任何特定限制;

3. 值的变动不需要引发类中其它任何成员的相应变化;

属性的使用条件则恰好跟变量相反,只要满足下面任何一个条件,就应该使用属性:

1. 要求字段只能读或者只能写;

2. 需要限制字段的取值范围;

3. 在改变一个字段的值的时候希望改变对象的其它一些状态;

qq_29099439
qq_29099439 此回复专业相信并且有耐心,值得推荐
6 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
c#里的get和set访问器,不写和只写get+set有区别吗?

get和set访问器可以提供验证功能,也可以设置属性的只读,有很多功能。但是,很多属性只写get和set,没有方法体,例如: public int BufferSize { get; set; } 这样的话跟不写get和set,即 public int BufferSize; 有什么区别啊?反正是都能读写,也没什么其它附加功能。请大神指教,实在是想不明白。。。

Model层里面的get和set问题

public string user_name { set { _loginname = value; } get { return _loginname; } } 和 public string user_name{set;get;}有什么区别?

C# 数组类型属性在set时转换类型问题

首先,我声明了一个byte数组 ![生命一个byte数组](https://img-ask.csdn.net/upload/201701/11/1484126465_105958.png) 然后,我声明了一个属性,类型是int数组,通过get set来获取设置前面的内部byte数组(set执行的函数是将一个int值拆成2个byte值转换后赋值给内部byte数组时长度翻一倍) ![set执行的函数是将一个int值拆成2个byte值转换后赋值给内部byte数组时长度翻一倍](https://img-ask.csdn.net/upload/201701/11/1484126504_855064.png) get没有任何问题。但是SET的时候,只能直接赋值数组,但不能通过索引单独设置属性具体索引的值,即 这样可以: ![这样可以](https://img-ask.csdn.net/upload/201701/11/1484126810_528941.png) 这样就不可以: ![这样就不可以](https://img-ask.csdn.net/upload/201701/11/1484126644_694351.png) 为什么?(个人认为是索引与内存堆栈的问题,这个问题是只能依靠索引器来解决吗?)如果有其他方式怎么解决呢?索引器也没用过,烦请举例说明。

C#通过get set进行计算

老师给的题目,已知三角形的三边,在claas 三角形里面只使用getset计算三角形面积。求代码。![图片](https://img-ask.csdn.net/upload/201609/27/1474984780_276552.png)

object-c get,set 要怎么重写

C#代码 public static string adminPaswd { get { if (stradminPaswd==null) { stradminPaswd=SQLite.Instance.adminPswd;//读取数据库 } return stradminPaswd; } set { stradminPaswd = value; SQLite.Instance.adminPswd = stradminPaswd;//写入数据库 } } 在下初学oc不知道以上功能用object-c 要怎么实现,请高手解答 希望实现效果 读取:string s = adminPaswd; 写入:adminPaswd = "123";

正在学习VC#,其中get和set的作用不太理解

正在学习VC#,其中get和set的作用不太理解,不用它们,像java那样只使用字段定义不行么

无法显式调用运算符或访问器

困扰了好久了。c#反汇编回来的程序报了2个错误, this.msc.add_Error(new DScriptControlSource_ErrorEventHandler(OnError)); this.msc.add_Timeout(new DScriptControlSource_TimeoutEventHandler(OnTimeout)); 错误 1 “MSScriptControl.DScriptControlSource_Event.Error.add”: 无法显式调用运算符或访问器 完整代码如下 ``` using MSScriptControl; using System; using System.Runtime.InteropServices; using System.Threading; public class ScriptEngine : IDisposable { public ScriptControl msc; public event RunErrorHandler RunError; public event RunTimeoutHandler RunTimeout; public ScriptEngine() : this(ScriptLanguage.VBscript) { } public ScriptEngine(ScriptLanguage language) { this.msc = new ScriptControlClass(); this.msc.UseSafeSubset = true; this.msc.Language = language.ToString(); this.msc.add_Error(new DScriptControlSource_ErrorEventHandler(OnError)); this.msc.add_Timeout(new DScriptControlSource_TimeoutEventHandler(OnTimeout)); } public void Dispose() { Marshal.ReleaseComObject(this.msc); } public object Eval(string expression, string codeBody) { this.msc.AddCode(codeBody); return this.msc.Eval(expression); } public object Eval(ScriptLanguage language, string expression, string codeBody) { if (this.Language != language) { this.Language = language; } return this.Eval(expression, codeBody); } private void OnError() { if (this.RunError != null) { this.RunError(); } } private void OnTimeout() { if (this.RunTimeout != null) { this.RunTimeout(); } } public void Reset() { this.msc.Reset(); } public object Run(string mainFunctionName, object[] parameters, string codeBody) { this.msc.AddCode(codeBody); return this.msc.Run(mainFunctionName, ref parameters); } public object Run(ScriptLanguage language, string mainFunctionName, object[] parameters, string codeBody) { if (this.Language != language) { this.Language = language; } return this.Run(mainFunctionName, parameters, codeBody); } public bool AllowUI { get { return this.msc.AllowUI; } set { this.msc.AllowUI = value; } } public ScriptLanguage Language { get { return (ScriptLanguage) Enum.Parse(typeof(ScriptLanguage), this.msc.Language, false); } set { this.msc.Language = value.ToString(); } } public int Timeout { get { return 0; } } public bool UseSafeSubset { get { return this.msc.UseSafeSubset; } set { this.msc.UseSafeSubset = true; } } } ```

C#测试类怎么写 (急用)???

求C#的测试类(急用) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { enum Sexkind { Male, Female } class Human { private string no; public string No { get { return no; } set { int y = int.Parse(no.Substring(0, 4)); if (no == null || no.Length != 12) throw new Exception("长度不到十二位"); else if (y > DateTime.Now.Year || y < DateTime.Now.Year - 100) throw new Exception("年份错误"); else no = value; } } public string Name { set; get; } public Sexkind Sex { set; get; } public int count { set; get; } public int Year { get { return int.Parse(no.Substring(0, 4)); } } public string Info { get { return No + "\t" + Name + "\t" + Sex; } } public Human() { count++; } public Human(string no, string name, Sexkind sex) { count++; No = no; Name = name; Sex = sex; } public void Show() { Console.WriteLine(Info); } public void SayHello() { Console.WriteLine("Hello, human!"); } public delegate void State(object sender, string message); public event State OnIdle; public event State OnWork; static void Main(string[] args) { Human hu = new Human("201902211122", "哇哈哈", Sexkind.Male); hu.Show(); hu.SayHello(); } } } }

请帮我把下面的C#翻译成vb.net,实在看不懂,谢谢

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.IO; namespace SyncChatServer { class User { public TcpClient client { get; private set; } public BinaryReader br { get; private set; } public BinaryWriter bw { get; private set; } public string userName { get; set; } public User(TcpClient client) { this.client = client; NetworkStream networkStream = client.GetStream(); br = new BinaryReader(networkStream); bw = new BinaryWriter(networkStream); } public void Close() { br.Close(); bw.Close(); client.Close(); } } }

从SQL(C#和实体框架)到mongodb(Go和mgo)

<div class="post-text" itemprop="text"> <p>I am coming today because I have to migrate from SQL (with entity framework) to MongoDb, however, the database side of programming is a field where I am not an expert and I would like to make the best choice for the evolution of the program I am working on.</p> <p>Let say I have this database schema (an idea, not the actual case) :</p> <p><a href="https://i.stack.imgur.com/KHOFb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KHOFb.png" alt="enter image description here"></a></p> <p>So I have a school. In this school, I have classes and, those classes have students. The foreign keys are the italic fields.</p> <p>It should give something like that in C#:</p> <pre><code>public class SchoolEntity { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid Id { get; set; } = new Guid(); public string Name { get; set; } [InverseProperty("School")] public virtual ICollection&lt;ClassTeachingEntity&gt; ClassTeachings { get; set; } } public class ClassTeachingEntity { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid Id { get; set; } = new Guid(); public Guid SchoolId { get; set; } public string Name { get; set; } public string Description { get; set; } [ForeignKey("SchoolId")] public virtual SchoolEntity School { get; set; } [InverseProperty("ClassTeaching")] public virtual ICollection&lt;StudyingEntity&gt; StudyingEntities { get; set; } } public class StudyingEntity { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid Id { get; set; } = new Guid(); [Index("UniqueStudyingRelation", Order = 1, IsUnique = true)] public Guid UserId { get; set; } [Index("UniqueStudyingRelation", Order = 2, IsUnique = true)] public Guid ClassTeachingId { get; set; } [ForeignKey("UserId")] public virtual UserEntity User { get; set; } [ForeignKey("ClassTeachingId")] public virtual ClassTeachingEntity ClassTeaching { get; set; } } public class UserEntity { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid Id { get; set; } = new Guid(); public string Firstname { get; set; } public string Lastname { get; set; } [InverseProperty("User")] public virtual ICollection&lt;StudyingEntity&gt; StudyingEntities { get; set; } } </code></pre> <p>My question is, first, is the current structure good? (I didn't designed it, it has been realized before I arrived and I am more a beginner than an expert in databases)</p> <p>The second question is, do I have to create just one document from my four different tables? Because, as far as I know, in mongodb, it's a JSON logic, so I can store nested objects right?</p> <p><strong>I don't know if this information matters but I will use Go with <a href="https://godoc.org/github.com/globalsign/mgo" rel="nofollow noreferrer">mongodb</a>, not C# anymore.</strong></p> <p>Thanks for your feedback</p> </div>

c#将一个对象转换成json

c#将一个对象转换成json class AllyRequestIO { /*//请求随机数 private String random { get; set; } //请求参数 private String iparams { get; set; }*/ public String token { get; set; } public int payType { get; set; } public Decimal amount { get; set; } public String use { get; set; } public String remark { get; set; } public String orgId { get; set; } public long merchantId { get; set; } public String pbucode { get; set; } public String accno { get; set; } public String accname { get; set; } public String bankcode { get; set; } public String ubankno { get; set; } public String cusno { get; set; } public int acctype { get; set; } } AllyRequestIO aio = new AllyRequestIO(); aio.token = "e993ffb0-54a7-4446-8b17-937f1454d214"; aio.payType = 1; aio.amount = (Decimal)111.00; aio.use = "余额充值"; aio.remark = "用户:超级管理员充值余额"; aio.orgId="DDA607C7-C875-4B3A-AA29-4D435F2A4295"; aio.merchantId = 1; aio.pbucode = "TEST"; aio.accno = "6225842255849524451"; aio.accname = "李四"; aio.bankcode = "CCB"; aio.ubankno = "衣冠庙支行"; aio.cusno = "3625"; aio.acctype = 2; 我要将aio转换成json,怎么做?

用不带参数的构造函数,怎么进行矩阵运算

老师给我留的作业。急!!! 题目如下: 设计一个矩阵类,重载其加、减、乘运算符,实现矩阵的相加、相减、相乘,并用Windows Form程序进行测试。 要求: 1)定义一个一维数组,用于存储矩阵的值。 2)定义两个私有成员变量存储矩阵行列值。 3)定义带有set\get访问器的两个属性,对行列值变量进行设置。 4)定义一个索引器返回指定某行某列的矩阵的元素,索引器只有get访问器。 5)定义一个不带参构造函数,根据输入行列属性值随机创建矩阵,随机值为(1-100之间的数)。 6)定义+,-,*的重载方法,实现两个矩阵的相加、相减、相乘。 7)定义一个方法,实现矩阵的转置。 **问题:** 1.一个不带参数的构造函数,怎么能让数组的行列数自定义呢?怎么可以对矩阵进行各种运算呢? 2.求大神帮帮忙,写个完整的代码我看看。头凸

关于vs code写C#的一些问题

请问在vs code中调试C#的时候,F5是调试控制台 好像没法输入值,每次都用终端dotnet run去跑,这个终端的有没有快捷键之类的?然后关于obj复制到bin的那个文件夹只读改掉了后面又变了回来。

C# 访问redis集群,怎么能够查到所有信息?

使用StackExchange.Redis.dll访问redis,redis环境是集群环境,但是我根据集群环境对外的ip和端口访问获取数据GetDataBase(),然后使用模糊查询的时候,查到的信息不全。这个代码应该怎么实现才能查到想要的所有信息。 其中cacheResultArr的长度为1,我从redis管理工具查到的不只是1条。 private static ConnectionMultiplexer redis; private static readonly object Locker = new object(); private IDatabase db { get; set; } public static ConnectionMultiplexer Manager { get { if (redis == null) { lock (Locker) { if (redis == null || !redis.IsConnected) { redis = GetManager(); } } } return redis; } } private static ConnectionMultiplexer GetManager(string connectionString = null) { if (string.IsNullOrEmpty(connectionString)) { connectionString = ConfigurationManager.AppSettings["redisAddress"]; } return ConnectionMultiplexer.Connect(connectionString); } public void Init() { //redis = ConnectionMultiplexer.Connect(connectString); db = Manager.GetDatabase(); LogInfoHelper.Write("-----初始化,连接Redis-----"); string kpatternAfc = ConfigurationManager.AppSettings["kpatternAfc"]; var script = "return redis.call('keys',@pattern)"; var prepared = LuaScript.Prepare(script); var cacheResult = db.ScriptEvaluate(prepared, new { pattern = kpatternAfc }); if (cacheResult.IsNull) { return; } else { string[] cacheResultArr = (string[])cacheResult; foreach (string key in cacheResultArr) { var entries = db.HashGetAll(key); foreach (var item in entries) { } } } }

C#封装字段问题:两者的区别

(1) private int a; public int A { get { return a; } set { a = value; } } (2) public int a { get; set; } 这两者分别什么意思?有什么区别?

无法显式调用运算符或访问器 无法对属性或索引器赋值

困扰了好久了。c#反汇编回来的程序报了2个错误, ``` this.msc.add_Error(new DScriptControlSource_ErrorEventHandler(OnError)); this.msc.add_Timeout(new DScriptControlSource_TimeoutEventHandler(OnTimeout)); ``` 提示:“MSScriptControl.DScriptControlSource_Event.Error.add”: 无法显式调用运算符或访问器 改成这样: ``` this.msc.Error += new DScriptControlSource_ErrorEventHandler(OnError); ``` 也一样不行,提示:无法对属性或索引器“MSScriptControl.IScriptControl.Error”赋值 -- 它是只读的 完整代码如下 ``` using MSScriptControl; using System; using System.Runtime.InteropServices; using System.Threading; public class ScriptEngine : IDisposable { public ScriptControl msc; public event RunErrorHandler RunError; public event RunTimeoutHandler RunTimeout; public ScriptEngine() : this(ScriptLanguage.VBscript) { } public ScriptEngine(ScriptLanguage language) { this.msc = new ScriptControlClass(); this.msc.UseSafeSubset = true; this.msc.Language = language.ToString(); this.msc.add_Error(new DScriptControlSource_ErrorEventHandler(OnError)); this.msc.add_Timeout(new DScriptControlSource_TimeoutEventHandler(OnTimeout)); } public void Dispose() { Marshal.ReleaseComObject(this.msc); } public object Eval(string expression, string codeBody) { this.msc.AddCode(codeBody); return this.msc.Eval(expression); } public object Eval(ScriptLanguage language, string expression, string codeBody) { if (this.Language != language) { this.Language = language; } return this.Eval(expression, codeBody); } private void OnError() { if (this.RunError != null) { this.RunError(); } } private void OnTimeout() { if (this.RunTimeout != null) { this.RunTimeout(); } } public void Reset() { this.msc.Reset(); } public object Run(string mainFunctionName, object[] parameters, string codeBody) { this.msc.AddCode(codeBody); return this.msc.Run(mainFunctionName, ref parameters); } public object Run(ScriptLanguage language, string mainFunctionName, object[] parameters, string codeBody) { if (this.Language != language) { this.Language = language; } return this.Run(mainFunctionName, parameters, codeBody); } public bool AllowUI { get { return this.msc.AllowUI; } set { this.msc.AllowUI = value; } } public ScriptLanguage Language { get { return (ScriptLanguage) Enum.Parse(typeof(ScriptLanguage), this.msc.Language, false); } set { this.msc.Language = value.ToString(); } } public int Timeout { get { return 0; } } public bool UseSafeSubset { get { return this.msc.UseSafeSubset; } set { this.msc.UseSafeSubset = true; } } } ```

C# SetPropertyVisible动态设置属性不可见,但不生效?如何使生效?

C# 通过 SetPropertyVisible 动态设置某个属性的可见性,无法生效? public static void SetPropertyVisible(object entity, string attrName, bool visible) { Type type = typeof(BrowsableAttribute); PropertyDescriptorCollection props = TypeDescriptor.GetProperties(entity); AttributeCollection attrs = props[attrName].Attributes; FieldInfo info = type1.GetField("browsable", BindingFlags.CreateInstance | BindingFlags.NonPublic | BindingFlags.Instance); info.SetValue(attrs[type], visible); } 比如要动态设置可见性的属性如下: private Color textColor; [Browsable(true)] public Color TextColor { get { return textColor; } set { textColor = value; } } 设置方法:SetPropertyVisible(this,"TextColor",false); 但是执行后,该属性依然是可见的,没有被隐藏,如何使不可见?

C# 使用VLC编写的播放器,使用libvlc_video_set_callbacks进入回调后报错

参考http://www.cnblogs.com/smartsensor/p/4343769.html 中的回调功能,想将视频的每一帧图片截取下来,代码如下 private const int _width = 1920; private const int _height = 1080; private const int _pixelBytes = 4; private const int _pitch = _width * _pixelBytes; private IntPtr _buff = IntPtr.Zero; private VideoLockCB _videoLockCB; private VideoUnlockCB _videoUnlockCB; private VideoDisplayCB _videoDisplayCB; private void button3_Click(object sender, EventArgs e) { if (_videoLockCB == null) _videoLockCB = new VideoLockCB(VideoLockCallBack); if (_videoUnlockCB == null) _videoUnlockCB = new VideoUnlockCB(VideoUnlockCallBack); if (_videoDisplayCB == null) _videoDisplayCB = new VideoDisplayCB(VideoDiplayCallBack); string pluginPath = System.Environment.CurrentDirectory + "\\plugins\\"; string plugin_arg = "--plugin-path=" + pluginPath; string[] arguments = { "-I", "dummy", "--ignore-config", "--no-video-title", plugin_arg }; IntPtr vlcInstance = libvlc_new(arguments);// IntPtr mediaInstance = libvlc_media_new_path(vlcInstance, "C:\\Users\\Administrator\\Videos\\Vive Cinema\\test.mp4"); IntPtr mediaPlayerInstance = libvlc_media_player_new_from_media(mediaInstance); // IntPtr render_wnd = this.panel1.Handle;// // libvlc_media_player_set_hwnd(mediaPlayerInstance, (Int64)render_wnd); libvlc_media_release(mediaInstance); libvlc_video_set_format(mediaPlayerInstance, "RV32", _width, _height, _pitch);//RGBA 颜色不对,YUYV显示错误,I420程序跳出 libvlc_video_set_callbacks(mediaPlayerInstance, _videoLockCB, _videoUnlockCB, _videoDisplayCB, IntPtr.Zero); libvlc_media_player_play(mediaPlayerInstance); /*Thread.Sleep(200); int length = libvlc_media_player_get_length(mediaPlayerInstance); int width = libvlc_video_get_width(mediaPlayerInstance); int height = libvlc_video_get_height(mediaPlayerInstance); Console.WriteLine("" + length + "," + width + "," + height); * */ } [DllImport("libvlc.dll", EntryPoint = "libvlc_media_player_new_from_media", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern IntPtr libvlc_media_player_new_from_media(IntPtr mediaInstance); [DllImport("libvlc.dll", EntryPoint = "libvlc_video_set_callbacks", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern void libvlc_video_set_callbacks(IntPtr mediaPlayInstance, VideoLockCB lockCB, VideoUnlockCB unlockCB, VideoDisplayCB displayCB, IntPtr opaque); [DllImport("libvlc.dll", EntryPoint = "libvlc_video_set_format", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern void libvlc_video_set_format(IntPtr mediaPlayerInstance, IntPtr chroma, UInt32 width, UInt32 height, UInt32 pitch); public delegate IntPtr VideoLockCB(IntPtr opaque, IntPtr planes); //解锁一个图片缓冲区 public delegate void VideoUnlockCB(IntPtr opaque, IntPtr picture, IntPtr planes); //显示图片 public delegate void VideoDisplayCB(IntPtr opaque, IntPtr picture); // 锁定一个图片缓冲区时先锁定,然后初始化这个缓冲区。 private IntPtr VideoLockCallBack(IntPtr opaque, IntPtr planes) { Lock(); _buff = Marshal.AllocHGlobal(_pitch * _height); Marshal.WriteIntPtr(planes, _buff);//初始化 return IntPtr.Zero; } private void VideoDiplayCallBack(IntPtr opaque, IntPtr picture) { } //解锁图片缓冲区 private void VideoUnlockCallBack(IntPtr opaque, IntPtr picture, IntPtr planes) { Marshal.FreeHGlobal(_buff);//释放缓冲区 Unlock(); } bool obj = false; private void Lock() { obj = true; } private void Unlock() { obj = false; } private bool Islock() { return obj; } 运行的时候,点击按钮后,会在VideoLockCallBack返回后报错,直接就不能运行了,帮忙看一下是什么原因,VLC版本位2.2.4

c#异步通信代码错误问题

public void ConnectCallback(IAsyncResult ar) { Socket client = (Socket)ar.AsyncState; client.EndConnect(ar); bool connect_flag = false; connect_flag = true; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 connectDone.Set(); } //vs的这段代码中 ,bool connect_flag的connect_flag报了一个警告错误,变量connect_flag已赋值,但是其值从未使用过。如何修改? public static MODEL.DataSourceVersionQuery BrowseDataSource_QueryVersionData() { MODEL.DataSourceVersionQuery result = new MODEL.DataSourceVersionQuery(); //获取数据包 string strPacket = BrowseDataSource_PrepareVersionPacket(); //向服务端提交查询版本信息 string str = DAL.socket.GetSocketData(strPacket); //DAL.socket.GetSocketData(strPacket) vs报了一个错误,非静态字段、方法或属性DAL.socket.GetSocketData(string)“要求对象引用。如何修改? 还有这个错误![图片说明](https://img-ask.csdn.net/upload/201509/16/1442412249_893824.png) 另外我想把DAL中的socket.cs的 public byte[] bytesReceived { get; set; }这段移动到Model中而不报错要如何修改? DAL中socket完整代码如下: using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.ComponentModel; using System.Data; using System.Windows.Forms; using System.Threading; namespace DAL { /// <summary> /// Socket接口 /// </summary> class socket { //Socket public Socket clientSocket; /// <summary> /// socket连接 /// </summary> /// <returns> /// true 成功 /// false 失败 /// </returns> public bool SocketConnect() { byte[] bytesReceived = new byte[256]; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束 //从配置文件获取IP string SocketIP = DAL.Common.ReadConfigString("Recover", "IP"); //从配置文件获取端口 int SocketPort = Convert.ToInt32(DAL.Common.ReadConfigString("Recover", "Port")); //创建IP地址 IPAddress IP = IPAddress.Parse(SocketIP); try { //创建socket实例 clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建网络端点 IPEndPoint ipEnd = new IPEndPoint(IP, SocketPort); //与目标终端连接 clientSocket.BeginConnect(ipEnd, new AsyncCallback(ConnectCallback), clientSocket);//调用回调函数 connectDone.WaitOne(); if (clientSocket.Connected) { return true; } else { return false; } } catch (Exception e) { string strError = ""; strError += "\r\n SocketIP = " + SocketIP.ToString(); strError += "\r\n SocketPort = " + SocketPort.ToString(); DAL.Common.WriteErrorLog(e, strError); return false; } } /// <summary> /// 异步连接的回调函数 /// </summary> /// <param name="ar"></param> public void ConnectCallback(IAsyncResult ar) { Socket client = (Socket)ar.AsyncState; client.EndConnect(ar); bool connect_flag = false; connect_flag = true; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 connectDone.Set(); } /// <summary> /// Socket发送数据 /// </summary> /// <param name="strSend"> /// 数据的内容 /// </param> public void SocketSend(string strSend) { Socket clientSocket; //发送创建套接字 int length = strSend.Length; Byte[] bytesSent = new byte[length]; clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { bytesSent = System.Text.Encoding.Default.GetBytes(strSend); //将字符串指定到指定Byte数组 clientSocket.BeginSend(bytesSent, 0, bytesSent.Length, 0, new AsyncCallback(SendCallback), clientSocket); //异步发送数据 ManualResetEvent sendDone = new ManualResetEvent(false);//发送结束 sendDone.WaitOne(); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } } public void SendCallback(IAsyncResult ar) //发送的回调函数 { ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束 Socket client = (Socket)ar.AsyncState; int bytesSend = client.EndSend(ar); //完成发送 sendDone.Set(); } /// <summary> /// Socket接收数据 /// </summary> /// <returns> /// 收到的数据 /// </returns> public string SocketReceive() { string result = ""; try { MemoryStream stream = new MemoryStream(); Byte[] bytesReceived = new Byte[256]; clientSocket.BeginReceive(bytesReceived, 0, bytesReceived.Length, 0, new AsyncCallback(ReceiveCallback), clientSocket); ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束 sendDone.WaitOne(); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } return result; } public void ReceiveCallback(IAsyncResult ar) { Socket client = (Socket)ar.AsyncState; //获取句柄 int bytesread = client.EndReceive(ar); if (bytesread > 0) { clientSocket.BeginReceive(bytesReceived, 0, bytesReceived.Length, 0, new AsyncCallback(ReceiveCallback), client); string content = Encoding.ASCII.GetString(bytesReceived, 0, bytesReceived.Length); } else { ManualResetEvent readDone = new ManualResetEvent(false); //读信号 readDone.Set(); } } /// <summary> /// Socket通信 /// </summary> /// <param name="strSend"> /// 发送的信息 /// </param> /// <returns> /// 包体的内容 /// </returns> public string GetSocketData(string strSend) { string strDatas = ""; string strResult = ""; string strExtLength = ""; try { //Socket连接 SocketConnect(); //发送信息 SocketSend(strSend); //接收服务器的信息 strResult = SocketReceive(); //获取扩展信息的长度 strExtLength = strResult.Substring(16, 12); int ExtLength = Convert.ToInt32(strExtLength); //扩展信息,暂不使用 //string strExtInfo = strResult.Substring(32, ExtLength); //获取包体的内容 strDatas = strResult.Substring(ExtLength + 32); //strDatas = decodedString; } catch (Exception e) { string strError = ""; strError += "\r\n strResult = " + strResult; strError += "\r\n strExtLength = " + strExtLength; DAL.Common.WriteErrorLog(e, strError); strDatas = ""; } return strDatas; } public string SocketReceiveFile(string FileName) { string result = ""; try { MemoryStream streamPacketLength = new MemoryStream(); Byte[] bytesPacketLength = new Byte[16]; clientSocket.Receive(bytesPacketLength, bytesPacketLength.Length, 0); streamPacketLength.Write(bytesPacketLength, 0, bytesPacketLength.Length); result = System.Text.Encoding.Default.GetString(streamPacketLength.ToArray()); int PacketLength = Convert.ToInt32(result); streamPacketLength.Close(); MemoryStream streamExtLength = new MemoryStream(); Byte[] bytesExtLength = new Byte[12]; clientSocket.Receive(bytesExtLength, bytesExtLength.Length, 0); streamExtLength.Write(bytesExtLength, 0, bytesExtLength.Length); result = System.Text.Encoding.Default.GetString(streamExtLength.ToArray()); int ExtLength = Convert.ToInt32(result); streamExtLength.Close(); MemoryStream streamProtocol = new MemoryStream(); Byte[] bytesProtocol = new Byte[4]; clientSocket.Receive(bytesProtocol, bytesProtocol.Length, 0); streamProtocol.Write(bytesProtocol, 0, bytesProtocol.Length); result = System.Text.Encoding.Default.GetString(streamProtocol.ToArray()); string Protocol = result; streamProtocol.Close(); MemoryStream streamExtInfo = new MemoryStream(); Byte[] bytesExtInfo = new Byte[ExtLength]; clientSocket.Receive(bytesExtInfo, bytesExtInfo.Length, 0); streamExtInfo.Write(bytesExtInfo, 0, bytesExtInfo.Length); result = System.Text.Encoding.Default.GetString(streamExtInfo.ToArray()); byte[] Buffer = Convert.FromBase64String(result); string strExtInfo = UTF8Encoding.UTF8.GetString(Buffer); streamExtInfo.Close(); MODEL.FileTrackQuery ExtInfo = new MODEL.FileTrackQuery(); ExtInfo = JsonConvert.DeserializeObject<MODEL.FileTrackQuery>(strExtInfo); if (ExtInfo.code == "00") { FileInfo fi = new FileInfo(FileName); DirectoryInfo di = fi.Directory; if (!di.Exists) { di.Create(); } FileStream streamPacketInfo = new FileStream(FileName, FileMode.Create); if (PacketLength > 0) { Byte[] bytesPacketInfo = new Byte[PacketLength]; int bytes = 0; do { bytes = clientSocket.Receive(bytesPacketInfo, bytesPacketInfo.Length, 0); streamPacketInfo.Write(bytesPacketInfo, 0, bytes); } while (bytes > 0); } streamPacketInfo.Close(); } clientSocket.Close(); string strLogFile = System.AppDomain.CurrentDomain.BaseDirectory + "debug.txt"; StreamWriter sw = new StreamWriter(strLogFile, true); sw.WriteLine("PacketLength : " + PacketLength.ToString()); sw.WriteLine("ExtLength : " + ExtLength.ToString()); sw.WriteLine("strExtInfo : " + strExtInfo); sw.WriteLine("ExtInfo.code : " + ExtInfo.code); sw.WriteLine("\n------------------------------------------------------------------------\n"); sw.Flush(); sw.Close(); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } return result; } public string GetSocketFile(string strSend, string FileName) { string strDatas = ""; string strResult = ""; string strExtLength = ""; try { //Socket连接 SocketConnect(); //发送信息 SocketSend(strSend); //接收服务器的信息 strResult = SocketReceiveFile(FileName); //获取扩展信息的长度 //strExtLength = strResult.Substring(16, 12); //int ExtLength = Convert.ToInt32(strExtLength); //扩展信息,暂不使用 //string strExtInfo = strResult.Substring(32, ExtLength); //获取包体的内容 //strDatas = strResult.Substring(ExtLength + 32); } catch (Exception e) { string strError = ""; strError += "\r\n strResult = " + strResult; strError += "\r\n strExtLength = " + strExtLength; DAL.Common.WriteErrorLog(e, strError); strDatas = ""; } return strDatas; } public byte[] bytesReceived { get; set; } } } MODEL完整代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MODEL { public enum ClientEditionEnum { Enterprise,//企业版 Personal,//个人版 Internal,//内部版 None,//error } /// <summary> /// 授权文件内容 /// </summary> public class AuthorizeFileInfo { public string startTime { get; set; } public string expiryTime { get; set; } public string licenseID { get; set; } public string licensePassword { get; set; } public string terminalID { get; set; } public string customName { get; set; } public string customID { get; set; } public AuthorizeFileInfo() { startTime = ""; expiryTime = ""; licenseID = ""; licensePassword = ""; terminalID = ""; customName = ""; customID = ""; } } /// <summary> /// 通用返回值 /// </summary> /// public class CommonResult { public string code { get; set; } public string message { get; set; } public CommonResult() { code = ""; message = ""; } } public class EnterpriseConfirmAuthorizeDatas { public string sessionID { get; set; } public EnterpriseConfirmAuthorizeDatas() { sessionID = ""; } } /// <summary> /// 企业版授权校验接口 /// </summary> public class EnterpriseConfirmAuthorizeResult { public string code { get; set; } public string message { get; set; } public EnterpriseConfirmAuthorizeDatas datas { get; set; } public EnterpriseConfirmAuthorizeResult() { code = ""; message = ""; datas = new EnterpriseConfirmAuthorizeDatas(); } } public class PersonalConfirmAuthorizeDatas { public string sessionID { get; set; } public string licenseInfo { get; set; } public PersonalConfirmAuthorizeDatas() { sessionID = ""; licenseInfo = ""; } } /// <summary> /// 个人版授权校验接口 /// </summary> public class PersonalConfirmAuthorizeResult { public string code { get; set; } public string message { get; set; } public PersonalConfirmAuthorizeDatas datas { get; set; } public PersonalConfirmAuthorizeResult() { code = ""; message = ""; datas = new PersonalConfirmAuthorizeDatas(); } } /// <summary> /// 鉴权信息,每次调用安全接口时使用 /// </summary> public class LicInfo { public string licenseID { get; set; } public string licensePassword { get; set; } public string terminalID { get; set; } public string deviceID { get; set; } public string sessionID { get; set; } public LicInfo() { licenseID = ""; licensePassword = ""; terminalID = ""; deviceID = ""; sessionID = ""; } } /// <summary> /// java引擎的参数 /// </summary> public class JavaEngineArg { public string licenseID { get; set; } public string licensePassword { get; set; } public string terminalID { get; set; } public string customName { get; set; } public string customID { get; set; } public string deviceID { get; set; } public JavaEngineArg() { licenseID = ""; licensePassword = ""; terminalID = ""; customName = ""; customID = ""; deviceID = ""; } } /// <summary> /// 用户登录接口(一),非安全接口 /// </summary> /// public class UserInfoUnSafe { public string userID { get; set; } public string userName { get; set; } public string departmentName { get; set; } public UserInfoUnSafe() { userID = ""; userName = ""; departmentName = ""; } } public class UserLoginUnSafe { public string code { get; set; } public string message { get; set; } public UserInfoUnSafe datas { get; set; } public UserLoginUnSafe() { code = ""; message = ""; datas = new UserInfoUnSafe(); } } /// <summary> /// 个人版用户登录接口,非安全接口 /// </summary> /// public class UserInfoForPersonal { public string userID { get; set; } public string userName { get; set; } public string departmentName { get; set; } public string licenseInfo { get; set; } public UserInfoForPersonal() { userID = ""; userName = ""; departmentName = ""; licenseInfo = ""; } } public class UserLoginForPersonal { public string code { get; set; } public string message { get; set; } public UserInfoForPersonal datas { get; set; } public UserLoginForPersonal() { code = ""; message = ""; datas = new UserInfoForPersonal(); } } /// <summary> /// 用户登录接口(二),安全接口 /// </summary> /// public class UserInfoSafe { public string userSessionID { get; set; } public string userID { get; set; } public string userName { get; set; } public string departmentName { get; set; } public string activeTime { get; set; } public UserInfoSafe() { userSessionID = ""; userID = ""; userName = ""; departmentName = ""; activeTime = ""; } } public class UserLoginSafe { public string code { get; set; } public string message { get; set; } public UserInfoSafe datas { get; set; } public UserLoginSafe() { code = ""; message = ""; datas = new UserInfoSafe(); } } /// <summary> /// 更新检查接口 /// </summary> /// public class SingleVersion { public string softID { get; set; } public int version { get; set; } public SingleVersion() { softID = ""; version = new int(); } } public class Versions { public List<SingleVersion> versions { get; set; } public Versions() { versions = new List<SingleVersion>(); } } public class VersionUpdate { public string softID { get; set; } public int version { get; set; } public string url { get; set; } public VersionUpdate() { softID = ""; version = new int(); url = ""; } } public class VersionCheck { public string code { get; set; } public string message { get; set; } public List<VersionUpdate> datas { get; set; } public VersionCheck() { code = ""; message = ""; datas = new List<VersionUpdate>(); } } /// <summary> /// 数据源信息查询接口 /// </summary> /// public class OptInfoQuery { public string createUserID { get; set; } public string createUserName { get; set; } public string createUserTime { get; set; } public OptInfoQuery() { createUserID = ""; createUserName = ""; createUserTime = ""; } } public class Period { public int cycle { get; set; } public int cycleUnit { get; set; } public string timer { get; set; } public Period() { cycle = 1; cycleUnit = 1; timer = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); } } public class StrategyConfig { public int backType { get; set; } public int taskType { get; set; } public Period config { get; set; } public StrategyConfig() { backType = 0; taskType = 1; config = new Period(); } } public class FilterFileSuffix { public string suffix { get; set; } public FilterFileSuffix() { suffix = ""; } } public class Scan { public int scanType { get; set; } public string root { get; set; } public bool scanHideFile { get; set; } public string verifyCompleteName { get; set; } public int verifyCompleteMaxCount { get; set; } public int verifyCompleteTimer { get; set; } public string fileAttrGainer { get; set; } public bool recordCanNotReadFileInfo { get; set; } public bool recordEmptyDirectory { get; set; } public bool recordEmptyFile { get; set; } public List<FilterFileSuffix> filterFileSuffix { get; set; } public Scan() { scanType = 2; root = ""; scanHideFile = false; verifyCompleteName = ""; verifyCompleteMaxCount = 5; verifyCompleteTimer = 10000; fileAttrGainer = "null"; recordCanNotReadFileInfo = false; recordEmptyDirectory = false; recordEmptyFile = false; filterFileSuffix = new List<FilterFileSuffix>(); } } public class DataSourceConfigQuery { public int status { get; set; } public int dataSourceType { get; set; } public string dataSourceID { get; set; } public string dataSourceName { get; set; } public string dataSourceDescription { get; set; } public Scan config { get; set; } public DataSourceConfigQuery() { status = 0; dataSourceType = 0; dataSourceID = ""; dataSourceName = ""; dataSourceDescription = ""; config = new Scan(); } } public class DatasQuery { public OptInfoQuery optInfo { get; set; } public StrategyConfig strategyConfig { get; set; } public DataSourceConfigQuery dataSourceConfig { get; set; } public DatasQuery() { optInfo = new OptInfoQuery(); strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigQuery(); } } public class DataSourceInfoQuery { public string code { get; set; } public string message { get; set; } public List<DatasQuery> datas { get; set; } public DataSourceInfoQuery() { code = ""; message = ""; datas = new List<DatasQuery>(); } } public class WebSite { public string ExpirationTime { get; set; } public string WebSiteSpace { get; set; } public bool DataBaseEnable { get; set; } public string DataBaseUserName { get; set; } public string DataBasePassword { get; set; } public string DataBaseMark { get; set; } public string WebSiteAdmin { get; set; } public string WebSitePassword { get; set; } public WebSite() { ExpirationTime = ""; WebSiteSpace = ""; DataBaseEnable = false; DataBaseUserName = ""; DataBasePassword = ""; DataBaseMark = ""; WebSiteAdmin = ""; WebSitePassword = ""; } } public class WebSiteDatasQuery { public OptInfoQuery optInfo { get; set; } public StrategyConfig strategyConfig { get; set; } public DataSourceConfigQuery dataSourceConfig { get; set; } public WebSite webSiteConfig { get; set; } public WebSiteDatasQuery() { optInfo = new OptInfoQuery(); strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigQuery(); webSiteConfig = new WebSite(); } } public class WebSiteDataSourceInfoQuery { public string code { get; set; } public string message { get; set; } public List<WebSiteDatasQuery> datas { get; set; } public WebSiteDataSourceInfoQuery() { code = ""; message = ""; datas = new List<WebSiteDatasQuery>(); } } /// <summary> /// 新增数据源接口 /// </summary> /// public class OptInfoNew { public bool forceFlag { get; set; } public OptInfoNew() { forceFlag = true; } } public class DataSourceConfigNew { public int dataSourceType { get; set; } public string dataSourceName { get; set; } public string dataSourceDescription { get; set; } public Scan config { get; set; } public DataSourceConfigNew() { dataSourceType = 0; dataSourceName = ""; dataSourceDescription = ""; config = new Scan(); } } public class DataSourceNew { public OptInfoNew optInfo { get; set; } public StrategyConfig strategyConfig { get; set; } public DataSourceConfigNew dataSourceConfig { get; set; } public DataSourceNew() { optInfo = new OptInfoNew(); strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigNew(); } } /// <summary> /// 修改数据源接口 /// </summary> /// public class DataSourceModify { public StrategyConfig strategyConfig { get; set; } public DataSourceConfigQuery dataSourceConfig { get; set; } public DataSourceModify() { strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigQuery(); } } /// <summary> /// 停用/启用数据源接口 /// </summary> /// public class DataSourceStatus { public string dataSourceID { get; set; } public int optType { get; set; } public DataSourceStatus() { dataSourceID = ""; optType = new int(); } } /// <summary> /// 数据源数据,仅用于存放数据 /// </summary> /// public class DataSourceData { public List<DatasQuery> datas { get; set; } public DataSourceData() { datas = new List<DatasQuery>(); } } /// <summary> /// WebSite数据源数据,仅用于存放数据 /// </summary> /// public class WebSiteDataSourceData { public List<WebSiteDatasQuery> datas { get; set; } public WebSiteDataSourceData() { datas = new List<WebSiteDatasQuery>(); } } /// <summary> /// 文件恢复,版本查询 /// </summary> /// public class DataSourceVersionArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 前置机编号 public string terminalId { get; set; } // 操作用户编号 public string optUserID { get; set; } public DataSourceVersionArg() { secretKey = ""; token = ""; terminalId = ""; optUserID = ""; } } public class FileVersions { public int file_count { get; set; } public long space_size { get; set; } public string task_id { get; set; } public string task_time { get; set; } public int total_count { get; set; } public string version { get; set; } public FileVersions() { file_count = new int(); space_size = new long(); task_id = ""; task_time = ""; total_count = new int(); version = ""; } } public class DataSourceVersion { public Scan datasourceConfig { get; set; } public string datasourceId { get; set; } public string datasourceName { get; set; } public int datasourceStatus { get; set; } public int datasourceType { get; set; } public List<FileVersions> versions { get; set; } public DataSourceVersion() { datasourceConfig = new Scan(); datasourceId = ""; datasourceName = ""; datasourceStatus = new int(); datasourceType = new int(); versions = new List<FileVersions>(); } } /// <summary> /// 查询数据源接口 /// </summary> public class DataSourceVersionQuery { public string code { get; set; } public string message { get; set; } public List<DataSourceVersion> datas { get; set; } public DataSourceVersionQuery() { code = ""; message = ""; datas = new List<DataSourceVersion>(); } } /// <summary> /// 数据源版本信息 /// </summary> public class DataSourceVersionDatas { public List<DataSourceVersion> datas { get; set; } public DataSourceVersionDatas() { datas = new List<DataSourceVersion>(); } } /// <summary> /// 文件恢复,文件信息查询 /// </summary> /// public class QueryFileInfoArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 数据源编号 public string datasourceId { get; set; } // 操作用户编号 public string optUserID { get; set; } // 目录文件编号--如果为根目录使用 DS_ROOT public string fileID { get; set; } // 查询的版本编号 如果是综合分析 这个字段设置为 ALL public string taskID { get; set; } public QueryFileInfoArg() { secretKey = ""; token = ""; datasourceId = ""; optUserID = ""; fileID = ""; taskID = ""; } } public class FileInfoCondition { public string datasourceId { get; set; } public string parentId { get; set; } public string taskID { get; set; } public FileInfoCondition() { datasourceId = ""; parentId = ""; taskID = ""; } } public class FileInfo { // 文件唯一编号 public string file_id { get; set; } // 源相对目录 public string file_src_path { get; set; } // 文件名 public string file_name { get; set; } // 文件后缀 public string file_suffix { get; set; } // 是否为文件 public bool is_file { get; set; } // 上级文件编号 public string parent_id { get; set; } // 是否删除 public bool is_del { get; set; } // 是否隐藏 public bool is_hide { get; set; } // 文件大小 public int size { get; set; } // 文件创建时间 public string create_time { get; set; } // 文件创建人 public string create_user { get; set; } // 文件最后修改时间 public string lm_time { get; set; } // 文件最后修改人 public string lm_user { get; set; } // 是否可读 public bool can_read { get; set; } public FileInfo() { file_id = ""; file_src_path = ""; file_name = ""; file_suffix = ""; is_file = new bool(); parent_id = ""; is_del = new bool(); is_hide = new bool(); size = new int(); create_time = ""; create_user = ""; lm_time = ""; lm_user = ""; can_read = new bool(); } } public class FileInfoAndCondition { public FileInfoCondition condition { get; set; } public List<FileInfo> fileInfos { get; set; } public FileInfoAndCondition() { condition = new FileInfoCondition(); fileInfos = new List<FileInfo>(); } } /// <summary> /// 查询文件信息接口 /// </summary> public class FileInfoQuery { public string code { get; set; } public string message { get; set; } public FileInfoAndCondition datas { get; set; } public FileInfoQuery() { code = ""; message = ""; datas = new FileInfoAndCondition(); } } /// <summary> /// 文件信息 /// </summary> public class FileInfoData { public List<FileInfo> datas { get; set; } public FileInfoData() { datas = new List<FileInfo>(); } } public class QueryFileTrackArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 文件编号 public string fileID { get; set; } // 操作用户编号 public string optUserID { get; set; } // 查询的版本编号 public string taskID { get; set; } public QueryFileTrackArg() { secretKey = ""; token = ""; fileID = ""; optUserID = ""; taskID = ""; } } public class FileTrack { // 文件操作 public string act_cmd { get; set; } // 是否可读 public bool can_read { get; set; } // 文件创建时间 public string create_time { get; set; } // 文件创建人 public string create_user { get; set; } // 是否删除 public bool is_del { get; set; } // 是否隐藏 public bool is_hide { get; set; } // 文件最后修改时间 public string lm_time { get; set; } // 文件最后修改人 public string lm_user { get; set; } // 文件大小 public int size { get; set; } public string taskID { get; set; } public FileTrack() { act_cmd = ""; can_read = new bool(); create_time = ""; create_user = ""; is_del = new bool(); is_hide = new bool(); lm_time = ""; lm_user = ""; size = new int(); taskID = ""; } } public class FileTrackCondition { public string fileID { get; set; } public string taskID { get; set; } public FileTrackCondition() { fileID = ""; taskID = ""; } } /// <summary> /// 查询文件轨迹接口 /// </summary> public class FileTrackQuery { public string code { get; set; } public string message { get; set; } public FileTrackCondition condition { get; set; } public List<FileTrack> datas { get; set; } public FileTrackQuery() { code = ""; message = ""; condition = new FileTrackCondition(); datas = new List<FileTrack>(); } } /// <summary> /// 文件轨迹 /// </summary> public class FileTrackData { public List<FileTrack> datas { get; set; } public FileTrackData() { datas = new List<FileTrack>(); } } /// <summary> /// 字典item /// </summary> public class DictionaryData { public string version { get; set; } public string task_time { get; set; } public DictionaryData() { version = ""; task_time = ""; } } public class FileRecoverArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 操作用户编号 public string optUserID { get; set; } public string fileID { get; set; } public string taskID { get; set; } public string password { get; set; } public FileRecoverArg() { secretKey = ""; token = ""; optUserID = ""; fileID = ""; taskID = ""; password = ""; } } }

c#如何循环取出对应属性名的值?

比如有个对象,里面有很多有序的属性名 public class myclass { public string day1{get;set;} ... 一直累加 ... public string day31{get;set;} } 取里面属性的时候,如何循环取出对应属性名的值,而不用一个一个手写? var myclass = new myclass(); ....省略过程代码 for(int i=1;i<31;i++) { str =myclass[0].day+i //这种写法是错误的 str = myclass[0]["day"+i] //这种写法也是错误的 }

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

为什么本科以上学历的人只占中国人口的5%,但感觉遍地都是大学生?

中国大学生占总人口不到5% 2017年,中国整体的本科率仅有5.9%;如果算上研究生,这一比例可以进一步上升到6.5% 为什么在国家统计局推出的这份年鉴中,学历的最高一阶就是到研究生,而没有进一步再统计博士生的数量的。 原因其实并不难理解,相比全国和各省整体人口体量,博士生的占比非常之低,属于绝对意义上的小概率样本。 这一点,我们从上表中的各省研究生占比情况也可以看出端倪。除北京、天津、上海三...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

程序员写出这样的代码,能不挨骂吗?

当你换槽填坑时,面对一个新的环境。能够快速熟练,上手实现业务需求是关键。但是,哪些因素会影响你快速上手呢?是原有代码写的不够好?还是注释写的不够好?昨夜...

外包程序员的幸福生活

今天给你们讲述一个外包程序员的幸福生活。男主是Z哥,不是在外包公司上班的那种,是一名自由职业者,接外包项目自己干。接下来讲的都是真人真事。 先给大家介绍一下男主,Z哥,老程序员,是我十多年前的老同事,技术大牛,当过CTO,也创过业。因为我俩都爱好喝酒、踢球,再加上住的距离不算远,所以一直也断断续续的联系着,我对Z哥的状况也有大概了解。 Z哥几年前创业失败,后来他开始干起了外包,利用自己的技术能...

带了6个月的徒弟当了面试官,而身为高级工程师的我天天修Bug......

即将毕业的应届毕业生一枚,现在只拿到了两家offer,但最近听到一些消息,其中一个offer,我这个组据说客户很少,很有可能整组被裁掉。 想问大家: 如果我刚入职这个组就被裁了怎么办呢? 大家都是什么时候知道自己要被裁了的? 面试软技能指导: BQ/Project/Resume 试听内容: 除了刷题,还有哪些技能是拿到offer不可或缺的要素 如何提升面试软实力:简历, 行为面试,沟通能...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

记录下入职中软一个月(外包华为)

我在年前从上一家公司离职,没想到过年期间疫情爆发,我也被困在家里,在家呆着的日子让人很焦躁,于是我疯狂的投简历,看面试题,希望可以进大公司去看看。 我也有幸面试了我觉得还挺大的公司的(虽然不是bat之类的大厂,但是作为一名二本计算机专业刚毕业的大学生bat那些大厂我连投简历的勇气都没有),最后选择了中软,我知道这是一家外包公司,待遇各方面甚至不如我的上一家公司,但是对我而言这可是外包华为,能...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

Python爬虫,高清美图我全都要(彼岸桌面壁纸)

爬取彼岸桌面网站较为简单,用到了requests、lxml、Beautiful Soup4

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

6年开发经验女程序员,面试京东Java岗要求薪资28K

写在开头: 上周面试了一位女程序员,上午10::30来我们部门面试,2B哥接待了她.来看看她的简历: 个人简历 个人技能: ● 熟悉spring mvc 、spring、mybatis 等框架 ● 熟悉 redis 、rocketmq、dubbo、zookeeper、netty 、nginx、tomcat、mysql。 ● 阅读过juc 中的线程池、锁的源...

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

Java岗开发3年,公司临时抽查算法,离职后这几题我记一辈子

前几天我们公司做了一件蠢事,非常非常愚蠢的事情。我原以为从学校出来之后,除了找工作有测试外,不会有任何与考试有关的事儿。 但是,天有不测风云,公司技术总监、人事总监两位大佬突然降临到我们事业线,叫上我老大,给我们组织了一场别开生面的“考试”。 那是一个风和日丽的下午,我翘着二郎腿,左手端着一杯卡布奇诺,右手抓着我的罗技鼠标,滚动着轮轴,穿梭在头条热点之间。 “淡黄的长裙~蓬松的头发...

大牛都会用的IDEA调试技巧!!!

导读 前天面试了一个985高校的实习生,问了他平时用什么开发工具,他想也没想的说IDEA,于是我抛砖引玉的问了一下IDEA的调试用过吧,你说说怎么设置断点...

都前后端分离了,咱就别做页面跳转了!统统 JSON 交互

文章目录1. 无状态登录1.1 什么是有状态1.2 什么是无状态1.3 如何实现无状态1.4 各自优缺点2. 登录交互2.1 前后端分离的数据交互2.2 登录成功2.3 登录失败3. 未认证处理方案4. 注销登录 这是本系列的第四篇,有小伙伴找不到之前文章,松哥给大家列一个索引出来: 挖一个大坑,Spring Security 开搞! 松哥手把手带你入门 Spring Security,别再问密...

立即提问
相关内容推荐