简体   繁体   English

是否有可能使匿名类继承另一个类?

[英]Is it possible to make an anonymous class inherit another class?

This is a long shot, but I have a funny coding situation where I want the ability to create anonymous classes on the fly, yet be able to pass them as a parameter to a method that is expecting an interface or subclass. 这是一个很长的镜头,但我有一个有趣的编码情况,我希望能够动态创建匿名类,但能够将它们作为参数传递给期望接口或子类的方法。 In other words, I'd like to be able to do something like this: 换句话说,我希望能够做到这样的事情:

public class MyBase { ... }

public void Foo(MyBase something)
{
  ...
}

...
var q = db.SomeTable.Select(t =>
        new : MyBase // yeah, I know I can't do this...
        {
          t.Field1,
          t.Field2,
        });
foreach (var item in q)
  Foo(item);

Is there any way to do this other than using a named class? 除了使用命名类之外,还有什么方法可以做到这一点吗?

No. Anonymous types always implicitly derive from object , and never implement any interfaces. 不会。匿名类型总是隐式派生自object ,并且永远不会实现任何接口。

From section 7.6.10.6 of the C# 5 specificiation: 来自C#5规定的第7.6.10.6节:

An anonymous object initializer declares an anonymous type and returns an instance of that type. 匿名对象初始值设定项声明匿名类型并返回该类型的实例。 An anonymous type is a nameless class type that inherits directly from object . 匿名类型是直接从object继承的无名类类型。

So if you want a different base class or you want to implement an interface, you need a named type. 因此,如果您想要一个不同的基类, 或者您想要实现一个接口,则需要一个命名类型。

No. From the documentation : 不。从文档中

Anonymous types are class types that derive directly from object, and that cannot be cast to any type except object. 匿名类型是直接从对象派生的类类型,不能转换为除object之外的任何类型。

To solve your problem, just replace the anonymous type with normal class... 要解决您的问题,只需将匿名类型替换为普通类...

无法扩展匿名但您可以声明您的方法接受动态参数,如果您真的需要这个工作。

Short answer: no 简答:不

Long answer: You could use a C# proxy class. 答案很长:您可以使用C#代理类。 There are several tools that can proxy classes. 有几种工具可以代理类。 For example Moqs. 例如Moqs。 https://github.com/moq/moq4 https://github.com/moq/moq4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM