C# feature request: implement interfaces on anonymous types

前端 未结 10 1579
走了就别回头了
走了就别回头了 2021-02-19 06:57

I am wondering what it would take to make something like this work:

using System;

class Program
{
    static void Main()
    {
        var f = new IFoo { 
              


        
10条回答
  •  时光说笑
    2021-02-19 07:12

    Interesting idea, I'd be a little concerned that even if it could be done it might get confusing. E.g. when defining a property with non-trivial setters and getters, or how to disambiguate Foo if the the declaring type also contained a property called Foo.

    I wonder if this would be easier in a more dynamic language, or even with the dynamic type and DLR in C# 4.0?

    Perhaps today in C# some of the intent could be achieved with lambdas:

    void Main() {
        var foo = new Foo();
        foo.Bar = "bar";
        foo.Print = () => Console.WriteLine(foo.Bar);
        foo.Print();
    }
    
    
    class Foo : IFoo {
        public String Bar { get; set; }    
        public Action Print {get;set;}
    }
    

提交回复
热议问题