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

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

问题描述

我看到了关于如何在C#中创建mixins的各种问题,并且他们经常被指向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(动态关键字)。重新混合项目使用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类结构,不使用动态,接口上有扩展方法, href =http://msdn.microsoft.com/en-us/library/dd287757%28v=vs.100%29.aspx> 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天全站免登陆