一个C#匿名类可以实现接口? [英] Can a C# anonymous class implement an interface?

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

问题描述

是否有可能有一个匿名的类型实现一个接口。我有一张code的,我想工作,但不知道如何做到这一点。

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.

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

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