如何设置属性是否设置?在C#中。 [英] How to check property is set or not? In C#.

查看:87
本文介绍了如何设置属性是否设置?在C#中。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的类中有一些整数属性,我实例化了类并将某些属性设置为某个值,我没有设置一些属性,但是它的默认值为0,

所以我不想要那些没有设置的属性,

所以如何检查属性是否设置?

可以任何人建议我吗?



提前感谢

sushil



我有什么试过:



class Class1

{

public int SomePropery1 {get; set}

public int SomeMoreProp {get;设置;}

}



class1 c1 = new class1()

c1.SomePropery1 = 1;

Hi,
I have some integer properties in my class, i am instantiate the class and set some property to some value and I am not setting some property but its taking default value to 0,
so I don't want that not setted properties,
so how to check property is set or not?
can any one suggest me?

thanks in advance
sushil

What I have tried:

class Class1
{
public int SomePropery1{get; set}
public int SomeMoreProp{get; set;}
}

class1 c1 = new class1()
c1.SomePropery1 = 1;

推荐答案

尝试 null -able types:

http://www.dotnetperls.com/nullable-int [ ^ ]

使用可空类型(C#编程指南) [ ^ ]
Try null-able types :
http://www.dotnetperls.com/nullable-int[^]
Using Nullable Types (C# Programming Guide)[^]


如果这些整数属性具有一些一致的常规特性,并且您不想使用Nullable Int Type,正如Mehdi建议的那样,您可以做一些事情像这样
If these Integer Properties have some consistent regular feature, and you don't want to use the Nullable Int Type, as Mehdi suggested, you could do something like this
public class YourClass
{
    public const Int32 INTNOTSET = Int32.MinValue;

    public int Int1 { set; get; }

    public YourClass()
    {
        Int1 = INTNOTSET;
    }
}

然后你会测试属性是否初始化如下:

Then you would test if the property is initialized like this:

YourClass yourClass = new YourClass();

if (yourClass.Int1 == YourClass.INTNOTSET)
{
   // Int1 uninitialized 
}
else
{
   // Int1 value set  
}

注意,在'YourClass中将INTNOTSET定义为常量会导致它成为类的静态字段,必须通过对类本身的引用来访问它。



在不了解您的应用程序及其功能的更多信息,以及Int变量的共享方面及其用途(如果有)的情况下,评估相关性任何技术都是水晶球凝视:)但是,如果你的Int属性是为了保存从查询数据库返回的值,那么,你可能确实想要使用Nullable Int。



使用Nullable Types不会导致拳击和解拳,但会增加一些开销,但这里显示的技术或任何其他技术也是如此。



根据上下文,在一个场景中使用Dictionary< string,int>可能有用,等等。

Note that defining INTNOTSET as a Constant in 'YourClass results in it being a static Field of the Class which must be accessed via the reference to the Class itself.

Without knowing more about what your App is and what it does, and the shared aspects of your Int variables, and their uses (if any), evaluating the relevance of any technique is crystal-ball gazing :) However, if your Int Properties are there to hold values returned from querying databases, then, you probably do want to use Nullable Int.

Use of Nullable Types does not cause boxing and un-boxing, but does add some overhead, but so would the technique shown here, or any other technique.

Depending on the context, in one scenario using a Dictionary<string,int> might be useful, and so forth.


这篇关于如何设置属性是否设置?在C#中。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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