Home > Backend Development > C++ > Can Anonymous Types Implement Interfaces in C#?

Can Anonymous Types Implement Interfaces in C#?

Mary-Kate Olsen
Release: 2025-01-13 17:56:43
Original
154 people have browsed it

Can Anonymous Types Implement Interfaces in C#?

Discussion on implementing interfaces by anonymous classes

The following code example seems to imply that anonymous types can implement interfaces:

<code class="language-csharp">public interface DummyInterface
{
    string A { get; }
    string B { get; }
}

public class DummySource
{
    public string A { get; set; }
    public string C { get; set; }
    public string D { get; set; }
}

public class Test
{
    public void WillThisWork()
    {
        var source = new DummySource[0];
        var values = from value in source
                     select new
                     {
                         A = value.A,
                         B = value.C + "_" + value.D
                     };

        DoSomethingWithDummyInterface(values);
    }

    public void DoSomethingWithDummyInterface(IEnumerable<DummyInterface> values)
    {
        foreach (var value in values)
        {
            Console.WriteLine("A = '{0}', B = '{1}'", value.A, value.B);
        }
    }
}</code>
Copy after login

However, it should be noted that anonymous types cannot implement interfaces. The C# Programming Guide clearly states:

<code>匿名类型是包含一个或多个公共只读属性的类类型。不允许使用其他类型的类成员,例如方法或事件。匿名类型不能转换为除 object 之外的任何接口或类型。</code>
Copy after login

As a result, the provided code example will not compile because the anonymous type in the select expression cannot be converted to the DummyInterface type.

Another way to implement an interface using anonymous types is to use dynamic types, as described in the article "Dynamic Interface Wrapping". This involves creating a dynamic object that implements the required interface and wrapping the anonymous type within it. However, this approach has limitations because dynamic typing can introduce performance overhead and is more difficult to debug.

The above is the detailed content of Can Anonymous Types Implement Interfaces in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template