动态对象转换的语法替代方案

2024-04-29

我有一个 DynamicDictionary 的实现,其中字典中的所有条目都是已知类型:

public class FooClass
{
    public void SomeMethod()
    {
    }
}

dynamic dictionary = new DynamicDictionary<FooClass>();

dictionary.foo = new FooClass();
dictionary.foo2 = new FooClass();
dictionary.foo3 = DateTime.Now;  <--throws exception since DateTime is not FooClass

我想要的是在引用字典条目之一的方法时能够让 Visual Studio Intellisense 工作:

dictionary.foo.SomeMethod()  <--would like SomeMethod to pop up in intellisense

我发现做到这一点的唯一方法是:

((FooClass)dictionary.foo).SomeMethod()

谁能推荐一种更优雅的语法?我很乐意使用 IDynamicMetaObjectProvider 编写 DynamicDictionary 的自定义实现。

UPDATE:

有些人问为什么是动态的以及我的具体问题是什么。我有一个系统可以让我做这样的事情:

UI.Map<Foo>().Action<int, object>(x => x.SomeMethodWithParameters).Validate((parameters) =>
{
    //do some method validation on the parameters
    return true;  //return true for now
}).WithMessage("The parameters are not valid");

在这种情况下,方法 SomeMethodWithParameters 具有签名

public void SomeMethodWithParameters(int index, object target)
{
}

我现在注册单个参数验证的内容如下所示:

UI.Map<Foo>().Action<int, object>(x => x.SomeMethodWithParameters).GetParameter("index").Validate((val) =>
{
     return true;  //valid
}).WithMessage("index is not valid");

我想要的是:

UI.Map<Foo>().Action<int, object(x => x.SomeMethodWithParameters).index.Validate((val) =>
{
    return true;
}).WithMessage("index is not valid");

这可以使用动态,但在引用索引后您会失去智能感知 - 目前还好。问题是是否有一种巧妙的语法方法(除了上面提到的方法之外)让 Visual Studio 以某种方式识别类型。到目前为止听起来答案是否定的。

在我看来,如果有 IDynamicMetaObjectProvider 的通用版本,

IDynamicMetaObjectProvider<T>

这可以发挥作用。但没有,所以才有这个问题。


为了获得智能感知,你必须将某些东西转换为一个不是的值dynamic在某一点。 如果您发现自己经常这样做,您可以使用辅助方法来减轻痛苦:

GetFoo(dictionary.Foo).SomeMethod();

但这与您已经拥有的相比并没有多大改进。获得智能感知的唯一其他方法是将值转换回非动态类型或避免dynamic首先。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

动态对象转换的语法替代方案 的相关文章