方法参数和返回类型上的动态vs对象关键字 [英] dynamic vs object keyword on method params and return type

查看:55
本文介绍了方法参数和返回类型上的动态vs对象关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个非常基本的问题,请考虑以下方法:

A very basic question, consider this methods:

public object Foo(object bar) {... }

vs

public dynamic Bar(dynamic bar) {... }

实际上我没有这样的方法签名,为简化起见,此示例简化了操作,以显示两件事:方法参数中的'dynamic vs object'关键字和return关键字。

While practically I don't have method signature like this, this example simplified for brevity to show two things: 'dynamic vs object' keyword in method parameter and return's.

这两种方法会产生相同的IL或任何性能影响吗?

基于参考/遍历/示例,告诉动态是就像具有动态功能的对象一样,我猜两者都是同一回事,只是根据使用情况而有所不同,例如是否要在返回值上添加其他动态属性/方法。但是,我仍然想知道是否还要考虑其他关键事项。

请注意,如果我的班级中有 Bar 方法,并使用以下方法签名实现接口(反之亦然),编译器不会抱怨任何内容。

Note that if I have a class that has a Bar method like above and implement an interface with a method signature like below (or vice versa), the compiler does not complain anything.

object Bar(object bar);

存在大约3年后,我才有机会在类似这样的项目中使用动态功能创建动态存储库以供Web API使用并生成(动态)JSON。

After about 3 years of the existence, I just has a chance to use dynamic feature in a project like creating dynamic repository to be consumed by Web API and generate (dynamic) JSON.

public interface IRepository
{
    IEnumerable GetAll(string entityName, int skip, int take);
    int Count(string entityName);
    dynamic GetById(string entityName, int key);
    void Add(string entityName, dynamic entity);
    void Remove(string entityName, int key);
}

其中的实体不是具体的,并且 entityName code>在db列中定义。我还考虑使用 IEnumerable IEnumerable< dynamic> 。有想法吗?

Where an entity is not concrete and entityName is defined in a db column. I also considering either to use IEnumerable or IEnumerable<dynamic>. Any thought?

推荐答案

dynamic 在C#中被翻译为<$ c IL中的$ c> object

.method private hidebysig instance object Foo(object bar) cil managed
{...}

.method private hidebysig instance object Bar(object bar) cil managed
{
  .param [0]
  .custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor() = ( 01 00 00 00 ) 
  .param [1]
  .custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor() = ( 01 00 00 00 ) 
  ...
}

签名保持不变,仅将 Dynamic 属性添加到return和first参数。

The signature stays the same, only the Dynamic attribute is added to the return and first parameter.

如果可以将参数类型从 dynamic 更改为 object ,而无需进行任何更改其他代码。

If you can change the parameter type from dynamic to object without having to change any other code, do it.

这篇关于方法参数和返回类型上的动态vs对象关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆