Can method parameters be dynamic in C#

后端 未结 4 1643
南旧
南旧 2020-12-30 19:39

In c# 4.0, are dynamic method parameters possible, like in the following code?

public string MakeItQuack(dynamic duck)
{
  string quack = duck.Quack();
  ret         


        
相关标签:
4条回答
  • 2020-12-30 20:12

    Yes; see e.g.

    http://blogs.msdn.com/cburrows/archive/2008/11/14/c-dynamic-part-vi.aspx

    or Chris' other blogs. Or grab VS2010 Beta2 and try it out.

    0 讨论(0)
  • 2020-12-30 20:20

    See documentation http://msdn.microsoft.com/en-us/library/dd264741(VS.100).aspx

    0 讨论(0)
  • 2020-12-30 20:25

    Yes, you can absolutely do that. For the purposes of static overload resolution, it's treated as an object parameter (and called statically). What you do within the method will then be dynamic. For example:

    using System;
    
    class Program
    {
        static void Foo(dynamic duck)
        {
            duck.Quack(); // Called dynamically
        }
    
        static void Foo(Guid ignored)
        {
        }
    
        static void Main()
        {
            // Calls Foo(dynamic) statically
            Foo("hello");
        }
    }
    

    The "dynamic is like object" nature means you can't have one overload with just an object parameter and one with just a dynamic parameter.

    0 讨论(0)
  • 2020-12-30 20:30

    Yes, you can do that. As stated in C# 4.0 specification, the grammar is extended to support dynamic wherever a type is expected:

    type:
           ...
          dynamic

    This includes parameter definitions, of course.

    0 讨论(0)
提交回复
热议问题