简体   繁体   中英

c# create class instance using method inside class

I have a class called User, where one can initialize it like so:

User user = new User();

This works great, but in some cases I want to call a static method inside the User class, so that the code now looks like this:

User user = User.SomeMethod();

I am sure that it is not extremely difficult, because I have seen it done in System.Diagnostics.Process :

Process p = Process.Start("filename");

How can I make my class do the same?

EDIT:

This is what my class looks like:

public class User
    {
        public User()
        {
            // this runs when User u = new User() is called
        }

        public static void SomeMethod()
        {
            // I want this to run when "User u = User.SomeMethod() is called
        }
    }

Am I missing a method constructor?

Are you talking about something like this? There's no method constructor, but you can call the constructor from inside a method. You could also have a private constructor that is called from that method.

class User {
    ...

   public User() {}
   private User(string s) {
       // Can only be called inside User class
       Console.WriteLine(s);
   }

    public static User Create() {
        return new User("Creating user from method...");
    }
}

What you are trying to achieve is called a Factory pattern. Most of the cases you create a separate class, add Factory name into it and it will create User class for you. Use factory pattern if you want to control how the User class is created:

public class UserFactory
    {
        public static User CreateUser()
        {
            return new User();
        }
    }

Note: Above code is just simple explanation, there are more things about factory pattern and it is more complex than a few lines of code. If you need to learn more you can check the next link that will give you a detailed explanation.

If you want the User class to be responsible for creating itself via static method then look at the example below:

public class User
    {
        public string Name { get; set; }
        public string LastName { get; set; }
        public User()
        {

        }
        public static User CreateUser()
        {
            return new User();
        }
        public static User CreateUser(string name, string lastName)
        {
            return new User
            {
                Name = name,
                LastName = lastName
            };
        }
    }

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