混合与C#4.0

编程入门 行业动态 更新时间:2024-10-28 03:30:45
本文介绍了混合与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 =msdn.microsoft/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

本文发布于:2023-11-12 00:43:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580025.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!