我正在尝试创建一个上下文类来检测对属性的任何更改。我能够通过使用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?