简体   繁体   English

初始化属性的良好做法?

[英]Good practices for initialising properties?

I have a class property that is a list of strings, List. 我有一个类属性,它是一个字符串列表,List。 Sometimes this property is null or if it has been set but the list is empty then count is 0. However elsewhere in my code I need to check whether this property is set, so currently my code check whether it's null and count is 0 which seems messy. 有时这个属性为null或者如果已经设置但列表为空则count为0.但是我的代码中的其他地方我需要检查此属性是否已设置,所以当前我的代码检查它是否为null且count为0凌乱。

if(objectA.folders is null)
{
    if(objectA.folders.count == 0)
    {
      // do something
    }
}

Any recommendation on how this should be handled? 有关如何处理此事的任何建议? Maybe I should always initialise the property so that it's never null? 也许我应该总是初始化属性,以便它永远不会为空?

When I have List as a property, I usually have something that looks like the following (this is not a thread safe piece of code): 当我将List作为属性时,我通常会看到如下所示的内容(这不是一个线程安全的代码段):

public class SomeObject
{
    private List<string> _myList = null;

    public List<string> MyList
    {
        get
        {
            if(_myList == null)
                _myList = new List<string>();
            return _myList;
        }
    }
}

Your code would then never have to check for null because the Property would be initialized if used. 您的代码将永远不必检查null,因为如果使用属性将被初始化。 You would then only have to check for the Count. 然后,您只需要检查计数。

现在你的代码将始终抛出空指针异常,你正在检查Null,如果它是空的 - 你正试图访问一个不存在的对象。

If for your application the collection being a null reference never has a different meaning than the collection being empty, then yes, I would say you should always initialize it and this way remove the null checks from the remaining code. 如果对于您的应用程序,集合是空引用从不具有与集合为空的不同含义,那么是的,我会说您应该始终初始化它,这样就从剩余代码中删除空检查。

This approach only makes sense if the property setter does not allow to change it to a null reference after initialization. 如果属性设置器在初始化后不允许将其更改为空引用,则此方法才有意义。

You could always initialize the property so it's an empty List. 您始终可以初始化该属性,因此它是一个空列表。 Then you can just check the count property. 然后你可以检查计数属性。

List<String> Folder = Enumerable.Empty<String>();

I once wrote an extension method for ICollection objects that checked if they were null or empty 我曾经为ICollection对象编写了一个扩展方法,检查它们是否为null或为空

public static Boolean IsNullOrEmpty<T>(this ICollection<T> collection)
{
    return collection == null ? true : collection.Count() == 0;
}

public static Boolean IsPopulated<T>(this ICollection<T> collection)
{
    return collection != null ? collection.Count() > 0 : false;
}

You have three options (and you need to decide based on your project): 您有三个选项(您需要根据您的项目决定):

  1. Create a method to check for NullOrNoElements. 创建一个方法来检查NullOrNoElements。 Pro: Allows both null and no entries. Pro:允许null和no条目。 Con: You have to call it everywhere you want to use the property. Con:您必须在任何想要使用该属性的地方调用它。
  2. Preinitialize with a list. 使用列表进行预初始化。 Pro: Thread-save and very easy. Pro:线程保存非常简单。 Con: will use memory even when not used (depending on how many instances you have this may be a problem) Con:即使不使用也会使用内存(取决于你有多少个实例,这可能是个问题)
  3. Lazy initialize Pro: Does only use memory when really used. 懒惰初始化Pro:只在真正使用时才使用内存。 Con: NOT thread save. 骗局: 不是线程保存。
 private List<string> lp = null; public List<string> ListProp { get { if(lp == null) lp = new List<string>(); return lp; } } 

You could do this in a single IF 你可以在一个IF中完成这个

if(objectA.folders is null || objectA.folders.count == 0)

Or you could create a boolean property in the class which checks this status for you and returns a result 或者您可以在类中创建一个布尔属性,为您检查此状态并返回结果

public bool objectA.FolderIsNullOrEmpty
{
    get { return objectA.folders is null || objectA.folders.count == 0;}
}

If it does not make a difference to your application, I would rather recomend initializing the List to start with. 如果它对您的应用程序没有影响,我宁愿建议初始化List以开始。

You could handle this by initializing the object in the constructor. 您可以通过初始化构造函数中的对象来处理此问题。 This is usually where this type of thing is done. 这通常是完成此类事情的地方。 Although I see nothing wrong with your current code. 虽然我认为您当前的代码没有任何问题。 No point in initializing stuff that doesn't exist yet, it just wastes memory. 没有必要初始化那些尚不存在的东西,它只会浪费内存。

Its a good question. 这是一个很好的问题。 I would add a method to objectA FoldersNullOrEmpty() that you can use eg 我会为objectA FoldersNullOrEmpty()添加一个方法,你可以使用它

public virtual FoldersNullOrEmpty()
{
   return (folders == null || folders.count == 0)
}

I almost always initialize lists and even make sure they can't be set to null if exposed by any setters. 我几乎总是初始化列表,甚至确保如果任何setter暴露它们也不能设置为null。 This makes using them much easier. 这使得使用它们变得更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM