简体   繁体   中英

How to Extend a Sealed Class Property

Suppose you have in a compiled file (dll) a class that is sealed and this class has a public property that is read-only like this one:

public sealed class MyClass
{
    public MyClass();

    public Guid id { get; }
}

and then you add a reference to your project.

My question is: Is there any way to add to the Property id a setter?

What I really need is to assign a value to this property.

Let me explain this a little bit more. We have an independent web app (A) that uses two dlls which to operate well makes web service requests to an external app (B). The App B has 2 different dlls that almost contains the same classes. And the app A is using both dlls to make the requests. Now we are creating a new library for those classes that are “compatibles” each other (or at least have the same name) so that we have only one class to use. Now, I saw that in one dll this class MyClass has the property id read/write and, on the other hand, the other dll has the property just as read-only as I showed you earlier.

First disassemble the dll with reflector or similar. Then work out how the getter works. With a bit of luck it's reading a field and nothing else, but if it's doing anything more complicated then you'll have more to do in creating a setter. Lets say it is indeed a field and that field is called _privateGuidField .

The create a class that defines an extension method SetId(this MyClass obj, Guid newID) which gets the FieldInfo for that field and calls SetValue on it.

This will only work with fully-trusted code.

Then sit back and wait for the class whose code-guaranteed invariant you've just smashed apart to misbehave in a really weird way. Don't complain to the people who created the class if it does, because you've just torn their code apart so there's no point complaining if it no longer works.

There is no legal way of doing it: the class is sealed, and the property is read-only. If the class implements an interface with the id property, you could wrap that class into yours, and provide a getter and a setter. As it stands, however, your only choice is hacking through reflection, and it's not a valid choice at all. Depending on how the property is implemented, it may be impossible even with reflection.

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