- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我写了一个类,它允许派生类指定它的哪些属性可以延迟加载。代码是:
public abstract class SelfHydratingEntity<T> : DynamicObject where T : class {
private readonly Dictionary<string, LoadableBackingField> fields;
public SelfHydratingEntity(T original) {
this.Original = original;
this.fields = this.GetBackingFields().ToDictionary(f => f.Name);
}
public T Original { get; private set; }
protected virtual IEnumerable<LoadableBackingField> GetBackingFields() {
yield break;
}
public override bool TryGetMember(GetMemberBinder binder, out object result) {
LoadableBackingField field;
if (this.fields.TryGetValue(binder.Name, out field)) {
result = field.GetValue();
return true;
} else {
var getter = PropertyAccessor.GetGetter(this.Original.GetType(), binder.Name);
result = getter(this.Original);
return true;
}
}
public override bool TrySetMember(SetMemberBinder binder, object value) {
LoadableBackingField field;
if (this.fields.TryGetValue(binder.Name, out field)) {
field.SetValue(value);
return true;
} else {
var setter = PropertyAccessor.GetSetter(this.Original.GetType(), binder.Name);
setter(this.Original, value);
return true;
}
}
}
还有一个派生类:
public class SelfHydratingPerson : SelfHydratingEntity<IPerson> {
private readonly IDataRepository dataRepository;
public SelfHydratingDerivate(IDataRepository dataRepository, IPerson person)
: base(person) {
this.dataRepository = dataRepository
}
protected override IEnumerable<LoadableBackingField> GetBackingFields() {
yield return new LoadableBackingField("Address", () => this.dataRepository.Addresses.Get(this.Original.AddressID));
}
}
这对于获取和设置属性值非常有效,但是当我隐式转换时我得到一个 RuntimeBinderException 或一个 InvalidCastException 并将 SelfHydratingEntity 显式转换回 T。
我知道您可以重写 DynamicObject.TryConvert 方法,但我想知道到底要在这个方法中放入什么。我今天读了很多关于鸭子类型(duck typing)的文章,并尝试了几个库,但没有一个适用于这种特定情况。我今天尝试过的所有库都使用 Reflection.Emit 生成了一个包装器类,它调用“get_”和“set_”方法并自然地使用反射在包装的实例上找到这些方法。 SelfHydratingEntity 当然没有定义“get_”和“set_”方法。
所以,我想知道这种事情是否可能。有什么方法可以将 SelfHydratingEntity 的实例转换为 T 吗?我正在寻找这样的东西:
var original = GetOriginalPerson();
dynamic person = new SelfHydratingPerson(new DataRepository(), original);
string name = person.Name; // Gets property value on original
var address = person.Address; // Gets property value using LoadableBackingField registration
var iPerson = (IPerson)person;
- or -
var iPerson = DuckType.As<IPerson>(person);
最佳答案
你看到这个了吗Duck Typing项目。看起来不错。我刚找到一个 great example来自 Mauricio .它使用温莎城堡动态代理拦截方法调用
使用 Mauricio 的代码,下面的代码就像做梦一样工作
class Program
{
static void Main(string[] args)
{
dynamic person = new { Name = "Peter" };
var p = DuckType.As<IPerson>(person);
Console.WriteLine(p.Name);
}
}
public interface IPerson
{
string Name { get; set; }
}
public static class DuckType
{
private static readonly ProxyGenerator generator = new ProxyGenerator();
public static T As<T>(object o)
{
return generator.CreateInterfaceProxyWithoutTarget<T>(new DuckTypingInterceptor(o));
}
}
public class DuckTypingInterceptor : IInterceptor
{
private readonly object target;
public DuckTypingInterceptor(object target)
{
this.target = target;
}
public void Intercept(IInvocation invocation)
{
var methods = target.GetType().GetMethods()
.Where(m => m.Name == invocation.Method.Name)
.Where(m => m.GetParameters().Length == invocation.Arguments.Length)
.ToList();
if (methods.Count > 1)
throw new ApplicationException(string.Format("Ambiguous method match for '{0}'", invocation.Method.Name));
if (methods.Count == 0)
throw new ApplicationException(string.Format("No method '{0}' found", invocation.Method.Name));
var method = methods[0];
if (invocation.GenericArguments != null && invocation.GenericArguments.Length > 0)
method = method.MakeGenericMethod(invocation.GenericArguments);
invocation.ReturnValue = method.Invoke(target, invocation.Arguments);
}
}
关于c# - Duck Typing DynamicObject 派生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3349103/
关闭。这个问题不满足Stack Overflow guidelines .它目前不接受答案。 想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。 6年前关闭。 Improve thi
我习惯于动态类型意味着在运行时检查对象/非面向对象结构的类型信息并抛出某种类型错误,即如果它像鸭子类型(duck typing)一样嘎嘎叫,它就是一只鸭子类型(duck typing)。是否有不同类型
这是《Practical Object-Oriented Design in Ruby》书中的一个示例。我有兴趣将这个 ruby 代码翻译成 javascript,以便更好地理解 JS 中的鸭子类
我又在 Scala 闲逛,我希望这是一个关于鸭子类型的基本问题,或者它可能真的与函数定义有关。让我解释: 鉴于以下代码: package johnmcase.scala.oneoffs object
Typescript 在某些情况下执行“鸭子”键入,例如当您针对接口(interface)检查函数参数的有效性时。 例如: interface Named { name: string } fun
代替遍历集合,有时在过程上循环遍历它们更方便。为了避免根据输入区分$_和$_.Key / $_.Value,更一致的键/值处理将是不错的: ForEach-KV $object { Param($k,
我正在使用带有继承的面向对象方法来解决问题,并且我想知道如何将“鸭子类型(duck typing)”原则应用于此问题。 我有一个类 BoxOfShapes ,它将使用 Shapes 列表(Circle
我正在尝试找到一种方法来为继承一对相似接口(interface)的两个对象表达共同的基类型。 请看下面的代码:很明显,fb1 和 fb2 应该有一个可能的公共(public)基类型(例如,类似 IFi
我有一个使用参数元组创建类实例的“工厂”: def factory(cls, arg): return cls(*arg) class Foo(object): def __init__(se
我正在编写一个 Duck 类,这样创建的每个 Duck 对象都包含翼展和重量字段变量。每只鸭子都应该随机初始化这些中的每一个。翼展应初始化为 [80.0,100.0]cm 范围内的随机 float 。
我有一些代码可以在我的应用程序中实现音频闪避。当用户正在听一些音乐时,然后进入某个位置,将播放特定的音乐片段。发生这种情况时,正在播放的原始音乐“低声”(或变得更安静),而我的应用程序开始播放的新音乐
如 TypeScript 中所述 handbook : One of TypeScript’s core principles is that type-checking focuses on the
Python 有特定的 ABCs for container types .它说它们是,“……用于测试类是否提供特定接口(interface)。” (而且它们对某些混入也很有用,但我们暂时忽略它。)
问题 我现在已经阅读了很多关于 Duck Typing 的内容,并且我似乎理解了这个概念。 我不明白的是,在什么情况下放弃强类型化编程的好处而转向 Duck Typing 的好处实际上是有意义的。 在
我的文档太多了,因为每当我遇到一个复杂的鸭子类型(duck typing)时,我都需要某种方式来表达“这个鸭子类型(duck typing)”,但却陷入了“你的函数需要这个输入的这个”的无休止循环,但
在 Advantages of Exceptions Java™ 教程的部分: A method can duck any exceptions thrown within it, thereby a
在我目前的工作中,我正在构建一套严重依赖对象的 Perl 脚本。 (在哈希上使用 Perl 的 bless() 以尽可能接近 OO) 现在,由于缺乏更好的表达方式,我公司的大多数程序员都不是很聪明。更
Can I specify interfaces when I declare a member? 在考虑了这个问题一段时间后,我突然想到静态鸭子类型(duck typing)的语言可能真的有效。为什
我对这两个术语有点困惑,这就是我所知道的: 多态性是不同类型的对象由一个公共(public)接口(interface)处理的能力。而鸭子类型(duck typing),是一种动态类型,它允许不同类型的
所有动态语言都支持duck typing ? 我认为 PHP 支持鸭子类型(duck typing)。是这样吗? 最佳答案 任何动态类型的 oop 语言都支持鸭子类型(duck typing),包括
我是一名优秀的程序员,十分优秀!