0

I'm working on building a die rolling program for use in an XNA project I'm using, but my question here is purely c# and is more on best practices or any gotchas I might need to look out for. Is it an effective use of a static method in an object's definition to outline the creation of default items.

Below is the snapshot of the code I'm using,

public struct Die{
    private DieType die;
    private static Random rnd = new Random();
    public static Die d2 = new Die(DieType.d2);
    public static Die d4 = new Die(DieType.d4);
    public static Die d6 = new Die(DieType.d6);
    public static Die d8 = new Die(DieType.d8);
    public static Die d10 = new Die(DieType.d10);
    public static Die d12 = new Die(DieType.d12);
    public static Die d20 = new Die(DieType.d20);
    public static Die d100 = new Die(DieType.d100);

    public Die(DieType die){
        this.die = die;
    }

    public int Roll(){
        return rnd.Next((int)die);
    }
}

Using this my code seems to compile without issues when I make references to the Die struct:

List <Roll> diceCup = new List<Roll>();
diceCup.Add (new Roll(4,Die.d6,-Die.d6.Roll()));

Roll is another struct that takes a Quantity of Die to roll and a short to modify it by.

In the case of my sample above, I create a new roll of 4d6-d6.

Is this going to cause me any problems later down the line if I am creating new instances of these dice?

Thanks for the advice!

Andrew

4

1 回答 1

0

如果我想将它们用作方法组,我会在很多类中添加一个静态工厂方法:

var people = names.Select(Person.Create);

在这种情况下,我只需用一组静态属性和惰性单例替换一组不同的工厂方法:

public class Die
{
    private static Die _d2;

    public static Die D2
    {
        get
        {
            if(_d2 == null)
                _d2 = new Die(DyeType.D2);

            return _d2;
        }
    }

    private static Die _d3 ...

}

我使用这些而不仅仅是公共静态字段,因为我想将它们的创建延迟到第一次使用。

这可以通过以下方式简化:http Lazy<T>: //msdn.microsoft.com/en-us/library/dd642331.aspx

public class Die
{
    private static readonly Lazy<Die> _d2 = new Lazy<Die>(() => new Die(DyeType.D2));
    private static readonly Lazy<Die> _d3 = new Lazy<Die>(() => new Die(DyeType.D3));
    private static readonly Lazy<Die> _d4 = new Lazy<Die>(() => new Die(DyeType.D4));

    public static Die D2 { get { return _d2.Value; } }
    public static Die D3 { get { return _d3.Value; } }
    public static Die D4 { get { return _d4.Value; } }

    ...
}
于 2013-06-29T07:16:44.570 回答