Pregunta

I am writing a class with some functions and properties and texts in it.

I want that everyone who use my class can see the functions and texts and properties but could not change them.

How to do this first?

And in advanced I want that they can add some other functions and texts and properties to it, but could not change the existing ones that I wrote.

And how to do this next?

Update

There is a class that contains CRUD functions. Its created by a code generator that I have written. Now the people can add the created class and use its functions to do CRUD functions. I don't want to make it as a dll file as far as possible and I don't want to make the whole class readonly as far as possible again. I just want that when the people include the created class in their projects, they can add another function to it but they can not change or remove the functions which is generated with the code generator.

¿Fue útil?

Solución

I just want that when the people include the created class in their projects, they can add another function to it but they can not change or remove the functions which is generated with the code generator

Unfortunately you can't do this, once you distribute code a developer has complete control over it. It's generally not recommended to modify generated code anyway, however, it can actually work to your advantage if your code contains a bug or is not compatible and needs to be tweaked.

The best approach would be to make your generated code class partial which makes it much easier to extend e.g.

namespace My.Generated.Code
{
    public partial class GeneratedClass
    {
        ...
    }
}
...

namespace Some.Other.Project
{
    using My.Generated.Code;

    public partial class GeneratedClass
    {
        public string NewProperty { get; set; }

        public void NewMethod()
        {
        }
    }
}

As long as you don't make any of the properties in your generated class virtual then developers can add new behaviour/properties but can't modify existing.

Otros consejos

You could compile your class as .dll, so other user can add it to his project and cannot to change it. Also he could make inheritance and add his own methods without changing the parent class.

you can set this properties and methods as sealed it really depends on your needs.

have some time to read about C# modifiers http://msdn.microsoft.com/en-us/library/6tcf2h8w.aspx

Make your class as a base class or create an Interface/Abstract class and let other inherit it , they can add function/property/method but all things you did is as is unless it is virtual

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top