简体   繁体   中英

Do we need a keyword partial for all instantiation of partial classes?

Say I have an old class, dated from c# 1.1 and I would like to add more methods, fields to it. Now I am using 2005, and thus the most logical solution is to use partial classes. However, it seems that I have to pretend word partial to every class in a file where I define it.

The problem:

What if I cannot change the class declaration in an old file (add word partial to it), but still want to add methods to it, what should I do?

Well, firstly, yes you do need to use the partial keyword to all of the involved classes, under the same namespace. This will tell the compiler that those are the parts of the same class that will be put together.

Now, if you really cannot change the old classes, one thing you can do is to inherit your old class:

public class NewClass : OldClass

...and as such you can extend the functionality of the OldClass.

You may also choose to just consume the old class some sort of wrapper, as an attribute/property:

public class NewClass
{
    public OldClass MyClass { get; set; } //.NET 3.5 / VS2008

    private OldClass _oldClass; //.NET 2.0 / VS2005
    public OldClass MyClass
    {
       get { return _oldClass; }
       set { _oldClass = value; }
    }
}

...or even a generic:

public class NewClass<T> where T: OldClass //applicable in both versions

The suggestion for extension methods will also work:

public void NewMethod1(this OldClass, string someParameter){}  //available only in .NET 3.5/VS2008

您应该从中得出。

好吧,总有扩展方法。

Here is my order:

  1. Does extension method available for you? If you are on VS2005, that may be not.
  2. Then, you probably have to inherit from that class to add more methods.
  3. If the class is sealed, then you need wrap your class into another class with "composition patter".

You cannot do anything. You are not allowed to edit the old file, so you cannot add members to this file. Also you cannot add the partial keyword and add the members in another file.

The only ways out might be to write an extension methods (requires C# 3.0) or to create a derived class. Both solution do not (really) modify the original class.

If you're using VS2005 and you cannot modify the old class then really there is nothing you can do. If you were using VS2008 you could use extension methods to "simulate" adding new classes but nothing in 2005 will help you.

You're only possible option is really to subclass if possible and add new methods that way. Probably not going to fix the problem you're having though.

Why can you not change the old file? That seems fairly extreme.

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