匿名类可以实现接口吗? [英] Can anonymous class implement interface?

查看:119
本文介绍了匿名类可以实现接口吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用匿名类型实现接口?

Is it possible to have an anonymous type implement an interface?

我有一段我想工作的代码,但不知道该怎么做.

I've got a piece of code that I would like to work, but don't know how to do this.

我有几个答案,要么说不",要么创建一个实现接口的类,以构造该类的新实例.这并不是很理想,但是我想知道是否有一种机制可以在接口顶部创建一个瘦动态类,从而使这一过程变得简单.

I've had a couple of answers that either say no, or create a class that implements the interface construct new instances of that. This isn't really ideal, but I'm wondering if there is a mechanism to create a thin dynamic class on top of an interface which would make this simple.

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);
        }
    }
}

我找到了一篇文章动态界面包装描述了一种方法.这是最好的方法吗?

I've found an article Dynamic interface wrapping that describes one approach. Is this the best way of doing this?

推荐答案

否,匿名类型不能实现接口.从 C#编程指南:

No, anonymous types cannot implement an interface. From the C# programming guide:

匿名类型是由一个或多个公共只读属性组成的类类型.不允许使用其他种类的类成员,例如方法或事件.匿名类型不能强制转换为除对象之外的任何接口或类型.

Anonymous types are class types that consist of one or more public read-only properties. No other kinds of class members such as methods or events are allowed. An anonymous type cannot be cast to any interface or type except for object.

这篇关于匿名类可以实现接口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆