Вопрос

Im not sure if it is possible. I am running into a unique issue dealing with a clients api. I am needing to extend a class and add a bool property that does not exist in the base class.

below is an example of what I am trying to accomplish.

public class baseClass
{
    //.. No Editable Access
}

public class Extended
{
    public bool flaggedAsDeleted(this baseClass bc)
    {
        //Idealy was looking for get; set; but I know that don't work
        return true;// Need to know if possible to set property on baseClass or Alternative
    }

    public void flagAsDeleted(this baseClass bc)
    {
        flaggedAsDeleted = true;
    }
}

public class program
{
    public void doit()
    {
        baseClass bc = new baseClass();
        bc.flagAsDeleted();
    }

}
Это было полезно?

Решение

If you're trying to actually extend a class, you do it like this:

public class BaseClass
{
    //.. No Editable Access
}

public class Extended : BaseClass
{
    public bool FlaggedAsDeleted { get; set; }
}

If you're trying to add data to an existing class, you have two options:

  1. Inheritance - as seen above.

  2. Encapsulation - create a new object that holds an instance of the type you're adding to.


C# provides a feature called Extension Methods, which allows you to seemingly add methods to existing classes. However, these are really just syntactic sugar, as you're still constrained to the class's public API.

public class BaseClass
{
    public int Value { get; set; }
}

public static class ExtensionMethods
{
    public static void Increment(this BaseClass b)
    {
        b.Value += 1;
    }
}

Extension methods do not allow you to add data to an existing class though.

Другие советы

This is not unique. This is a common problem solved using a Design Pattern called decorator.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top