返回即兴对象作为类?

时间:2018-08-29 08:33:40

标签: c# impromptu-interface

我正在尝试创建一个上下文类,以检测对属性的任何更改。我可以使用 ImpromptuInterface 包来实现这一目标。

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...
}

我想实现的是我的方法返回一个类而不是一个接口。

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;  }
}

在我的Class类中,我的代理对象返回一个IAuthor,因为那是ImpromptuInterface所需要的。但是我是否可以将IAuthor强制转换回Author,以便GetAuthor方法返回Author对象,并且仍然实现INotifyPropertyChanged?

0 个答案:

没有答案