简体   繁体   中英

C# Passing object class as Method Parameter

I was reading some C# tutorial, and suddenly it strikes me that I have never attempted to use object class as parameter when creating a method.

For example, I would have never thought of this:

static void GiveBookAName(Gradebook book, string bookName)
{
    book.Name = bookName;
}

I am sure I would have done something like this:

public void GiveBookAName(string bookName)
{
     Name = bookName;
}

//in other class
Gradebook book = new Gradebook()
book.GiveBookAName("TheGradebook");

Because of that, I tend to have Class instantiation here and there. What I meant is, if I need to access Class X in Class A & B, then I will instantiate Class X in both Class A & B. Now I realize if I start passing object class as parameter, I can have all my instantiations in one place (usually the class with Main() ). Is that necessary?

It all depends all the context. The general rule of this kind of stuff is, if you think it makes sense to do this, then do it .

In your book naming method, I don't think you should pass the book as a parameter. Users of your API should be able to name the books using this:

book.Name = someStuff;

So you should not the book-naming method in another class because why should it be? The other class is not responsible for naming a book, right? Then let the book do it! Put the naming method in the Book class.

Actually I don't really pass object class as a parameter. I think that is the "functional" way of doing things, not object-oriented.

Let us look at another situation. You are using a class called X in the core library and you want to add a method to X . Now you might think you should pass an X object to the method like did with the Book because you certainly can't edit a class in core library! So this is your method:

public void DoStuffWithX(X x, int param) {

}

And you put this in another class. Well since C# 3, extension methods are added so you can do something like this:

public static void DoStuff (this X x, int param) {

}

Now you can call this method with an X object!

x.DoStuff(10);

Also I see that you always need to instantiate a class you access the method. By the nature of these "passing object class as parameter" methods, they should not have to be instantiated before calling. In other words, you should mark them static so that you can call it like this:

YourClassName.SomeMethod (parameter);

instead of:

YourClassName obj = new YourClassName ();
obj.SomeMethod (parameter);

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