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>
However, it should be noted that anonymous types cannot implement interfaces. The C# Programming Guide clearly states:
<code>匿名类型是包含一个或多个公共只读属性的类类型。不允许使用其他类型的类成员,例如方法或事件。匿名类型不能转换为除 object 之外的任何接口或类型。</code>
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!