与 C# 4.0 混合 [英] Mixins with C# 4.0

查看:31
本文介绍了与 C# 4.0 混合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了关于是否可以在 C# 中创建 mixin 的各种问题,并且它们通常被定向到 codeplex 上的重新混合项目.不过,我不知道我是否喜欢完整界面"的概念.理想情况下,我会像这样扩展一个类:

I've seen various questions regarding if mixins can be created in C# and they are often directed to the re-mix project on codeplex. However, I don't know if I like the "complete interface" concept. Ideally, I would extend a class like so:

    [Taggable]
    public class MyClass
    {
       ....
    }

通过简单地添加 Taggable 接口,我可以通过某种对象工厂创建 MyClass 类型的对象.返回的实例将包含在 MyClass 中定义的所有成员以及通过添加标记属性(如标记集合)提供的所有成员.使用 C# 4.0(dynamic 关键字)似乎很容易做到这一点.重新混合项目使用 C# 3.5.有没有人有通过 C# 4.0 扩展对象而不改变类本身的好方法?谢谢.

By simply adding the Taggable interface, I can create objects of type MyClass via some kind of object factory. The returned instance would have all the members defined in MyClass as well as all members provided by adding the tagging attribute (like a collection of tags). It seems like this would be easily doable using C# 4.0 (the dynamic keyword). The re-mix project uses C# 3.5. Does anyone have any good ways to extend objects via C# 4.0 without altering the classes themselves? Thanks.

推荐答案

您可以在 C# 4.0 中创建类似 mixin 的构造,而无需使用动态、接口上的扩展方法和 ConditionalWeakTable 类来存储状态.看看这里的想法.

You can create mixin-like constructs in C# 4.0 without using dynamic, with extension methods on interfaces and the ConditionalWeakTable class to store state. Take a look here for the idea.

这是一个例子:

public interface MNamed { 
  // required members go here
}
public static class MNamedCode {
  // provided methods go here, as extension methods to MNamed

  // to maintain state:
  private class State { 
    // public fields or properties for the desired state
    public string Name;
  }
  private static readonly ConditionalWeakTable<MNamed, State>
    _stateTable = new ConditionalWeakTable<MNamed, State>();

  // to access the state:
  public static string GetName(this MNamed self) {
    return _stateTable.GetOrCreateValue(self).Name;
  }
  public static void SetName(this MNamed self, string value) {
    _stateTable.GetOrCreateValue(self).Name = value;
  }
}

像这样使用它:

class Order : MNamed { // you can list other mixins here...
  ...
}

...

var o = new Order();
o.SetName("My awesome order");

...

var name = o.GetName();

使用属性的问题是不能将泛型参数从类传递到mixin.您可以使用标记界面来做到这一点.

The problem of using an attribute is that you can't flow generic parameters from the class to the mixin. You can do this with marker interfaces.

这篇关于与 C# 4.0 混合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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