简体   繁体   中英

How do I use a factory generated object?

I am a student trying to learn factory methods in C# and I would love some help. I now have a CommanderFactory that creates a "Commander()". Let's say I generate a "Commander()" with both values set to 1. (val1 = 1, val2 = 2). How Would I now go about doing calculations on these values? As seen in the calculator class above. I have a parameter for "Commander", but how do I "select" the values inside, and do addition on them?

namespace FactoryCalculator
{
    public static class Calculator
    {
        public static int Add(Commander)
        {
            return val1 + val2;
        }

    }

    public class Commander
    {
        private Commander()
        {
        }

        public int Val1 { get; set; }
        public int Val2 { get; set; }

        public static class CommanderFactory
        {
            public static Commander CreateNewCommander(int val1, int val2)
            {
                return new Commander()
                {
                    Val1 = val1,
                    Val2 = val2
                };
            }

        }
    }
}

This is the syntax for accessing a Property ([instance].[property]):

public static int Add(Commander c)
{
    return c.Val1 + c.Val2;
}

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