Returning Impromptu Object As Class?

173 views Asked by At

I am trying to create a context class that detects any changes to a property. I was able to achieve this by using the ImpromptuInterface package.

public class DynamicProxy<T> : DynamicObject, INotifyPropertyChanged  where T : class, new()
{
    private readonly T _subject;
    public event PropertyChangedEventHandler PropertyChanged;

    public DynamicProxy(T subject)
    {
        _subject = subject;
    }

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(_subject, new PropertyChangedEventArgs(propertyName));
    }

    public static I As<I>() where I : class
    {
        if (!typeof(I).IsInterface)
            throw new ArgumentException("I must be an interface type!");

        return new DynamicProxy<T>(new T())
            .ActLike<I>();
    }

    // Other overridden methods...
}

What I would like to achieve though is for my method to return a class and not an interface.

public class Class<T>
{
    public IAuthor GetAuthor()
    {
        var author = new Author
        {
            Id = 1,
            Name = "John Smith"
        };

        var proxy = DynamicProxy<Author>.As<IAuthor>();

        return proxy;
    }
}

static void Main(string[] args)
{
    Class<Author> c = new Class<Author>();
    var author = c.GetAuthor(); // Can I do something to change this to type Author?
    author.Name = "Sample"; //This code triggers the OnPropertyChangedMethod of DynamicProxy<T>

    Console.ReadLine();
}

public interface IAuthor : INotifyPropertyChanged
{
    int Id { get; }
    string Name { get; set;  }
}

In my Class class my proxy object returns an IAuthor because that is what ImpromptuInterface requires. But is it possible for me to cast IAuthor back to Author so that the GetAuthor method returns an Author object and will still have INotifyPropertyChanged implemented?

0

There are 0 answers