简体   繁体   中英

static property which returns class instance

I would like to use something similar as link ! Part of the source code looks like that:

public struct Vector3
{
    public static Vector3 zero { get; }
}

This function returns an already initialized Vector (which 0 on every axis). Is this possible, because it is a struct? That's what I have:

public class WorldBlock
{
    public enum e_WorldBlockType
    {
        Undef,
        Earth,
        Stone,
        Air // no block set
    }

    public static WorldBlock Empty { get; }
    public e_WorldBlockType BlockType { get; set; }
    public bool IsWalkable { get; set; }

    public WorldBlock(e_WorldBlockType blockType = e_WorldBlockType.Undef, bool isWalkable = false)
    {
        this.BlockType = blockType;
        this.IsWalkable = isWalkable;
    }
}

But I get this: error CS0840: 'WorldBlock.Empty.get' must have a body because it is not marked abstract or extern. The property can be automatically implemented when you define both accessors error CS0840: 'WorldBlock.Empty.get' must have a body because it is not marked abstract or extern. The property can be automatically implemented when you define both accessors

How should I write the body?

EDIT: If I add for example a private set , it compiles, but if I use it, I get a null pointer exception.

Something like this:

private static WorldBlock __empty = ...;

public static WorldBlock Empty {
  get {
    return WorldBlock __empty;
  }
}

If you only want an empty WorldBlock I suggest you write:

public static readonly WorldBlock Empty = new WorldBlock();

Instead of your Property. However it's kind of dodgy since the setters of the "Empty" object is public, so there's really no guarantee that it's actually empty.

You have to do:

public static WorldBlock Empty
{
  get{return someThing; }
}

Replace someThing with whatever you were wanting Empty to store.... If thats null or whatever.

From your title... it looks like you want to return an instance of the class. If you only ever want one instance of this class... you're looking for the Singleton design pattern.

Should your "Empty" instances be shared and be the same? If so, the following body is probably what you are looking for.

private static WorldBlock emptyInstance;
public static WorldBlock Empty
{
   get
   {
      if (emptyInstance == null)
      {
         //initialize it
      }
      return emptyInstance;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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