C# feature request: implement interfaces on anonymous types

前端 未结 10 1582
走了就别回头了
走了就别回头了 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:10

    As long as we're putting out an interface wish list, I'd really like to be able to tell the compiler that a class implements an interface outside the class definition- even in a separate assembly.

    For example, let's say I'm working on a program to extract files from different archive formats. I want to be able to pull in existing implementations from different libraries — say, SharpZipLib and a commercial PGP implementation — and consume both libraries using the same code without creating new classes. Then I could use types from either source in generic constraints, for example.

    Another use would be telling the compiler that System.Xml.Serialization.XmlSerializer implements the System.Runtime.Serialization.IFormatter interface (it already does, but the compiler doesn't know it).

    This could be used to implement your request as well, just not automatically. You'd still have to explicitly tell the compiler about it. Not sure how the syntax would look, because you'd still have to manually map methods and properties somewhere, which means a lot of verbiage. Maybe something similar to extension methods.

提交回复
热议问题