我们在C#中的模态类中有一个可选变量吗? [英] Do we have a optional variable in a modal class in C#

查看:55
本文介绍了我们在C#中的模态类中有一个可选变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们能否在下面的类中将它作为Optional变量提供。因为我不希望Obj1,obj2,obj3用于请求类型,但需要另一个请求。请建议我。



 public Obj1 IsForecasted {get;组; } 
public obj2? IsGenerated {get;组; }
public obj3? IsPosted {get;组; }
公共长? startDate {get;组; }
公共长? endDate {get;组; }
public int?[] s1 = new int?[6] {0,0,0,0,0,0};
public int?[] s2 = new int?[6] {0,0,0,0,0,0};
public int?[] s3 = new int?[6] {0,0,0,0,0,0};
public int?[] s4 = new int?[6] {0,0,0,0,0,0};





我的尝试:



我试图将[可选]添加为数据注释但不允许,因为它仅适用于参数。

解决方案

你不能拥有类中的可选数据 - 类实例是固定大小,不能更改。想一想:你有一个可选的值,而不是mode == normal - 所以你创建了一个类的实例作为普通实例。

后来你改变了值模式为高级并尝试使用可选值。额外空间来自哪里?它无法创建,因为实例是固定大小,分配的空间不包括您的可选字段。

结果:您的应用程序崩溃了!



不,C#中没有可选字段。


你需要什么可选变量?

如果你的班级应该有这个用法1的变量,不需要一些用于变量的变量2我不明白这个问题。

如果你不需要变量那么就不要使用它们。

如果变量(在我的代码片段中我将其视为属性)应具有默认值,则使用具有起始值的属性的内部变量:

  public   int  BorderSize {
get { return my_BorderSize; }
set {my_BorderSize = value ; }
}
private int my_BorderSize = 1 ;


Can we able to give it as a Optional variable in the below class. Because I don't want Obj1, obj2, obj3 for request type but needed for another request. Kindly suggest me.

public Obj1 IsForecasted { get; set; }
     public obj2 ? IsGenerated { get; set; }
     public obj3 ? IsPosted { get; set; }
     public long? startDate { get; set; }
     public long? endDate { get; set; }
     public int?[] s1= new int?[6] { 0, 0, 0, 0, 0, 0 };
     public int?[] s2= new int?[6] { 0, 0, 0, 0, 0, 0 };
     public int?[] s3= new int?[6] { 0, 0, 0, 0, 0, 0 };
     public int?[] s4= new int?[6] { 0, 0, 0, 0, 0, 0 };



What I have tried:

I have tried to add [Optional] as a data annotation but its not allowed because it only applicable for parameters.

解决方案

You can't have optional data in a class - a class instance is a fixed size and cannot be altered. Think about it: you have a optional value which is not there for "mode == normal" - so you create an instance of the class as a "normal" instance.
Later you change the value of mode to "advanced" and try to use the optional value. Where does the extra space come from? It can't be created because the instance is a fixed size and the space allocated did not include your optional field.
Result: your app crashes!

No, there are no optional fields in C#.


For what do you need such "optional Variables" ?
If your class should have this Variables for the usage 1 and needs not some Variables for usage 2 I don't understand the problem.
If you don't need the Variables then don't use them.
If the Variables (in your code-snippet I see them as Properties) should have default Values then use an internal Variable for the Property which has a Start-Value :

public int BorderSize {
	get { return my_BorderSize; }
	set { my_BorderSize = value; }
}
private int my_BorderSize = 1;


这篇关于我们在C#中的模态类中有一个可选变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆