C#通过添加属性来扩展类 [英] C# Extend class by adding properties

查看:1210
本文介绍了C#通过添加属性来扩展类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中是否可以不通过仅添加函数而是通过属性来扩展类.例如:我有一个我依赖的标准DLL库,供应商不想对其进行修改.

Is it possible in C# to extend a class not by adding only functions but properties. Ex: i have a standard DLL library I am relying on and the vendor does not want to modify it.

在整个代码中,我已经广泛使用了DataCell类,直到现在才意识到我需要为其添加一个额外的属性,因为创建从该类继承的新扩展类看起来并不可行+很多重写.

Already throughout the code I have used the DataCell class extensively and only now realized that I need to add an extra property to it, as creating a new extension class that inherits from this class just does not look like it would work + a lot of rewriting.

DataCell [元数据]

DataCell [metadata]

public class DataCell : Message
{
public int Field1;
public int Field2;
public DataCell()
{
 ..
} 
..
}

基本上我想添加一个公共int标志;上这堂课.因此,我现在无需重写任何内容即可(新的DataCell).Flags= 0x10;

Basically I want to add a public int Flags; to this class. So I can do now without rewriting anything, (new DataCell).Flags = 0x10;

推荐答案

首先,您可能应该重新考虑您的方法. 但是,如果其他所有方法均失败,则可以通过以下方法各种将属性添加到密封的类中:

First of all, you should probably reconsider your approach. But if all else fails, here is how you can sort of add a property to a sealed class:

using System;
using System.Runtime.CompilerServices;

namespace DataCellExtender
{

    #region sample 3rd party class
    public class DataCell
    {
        public int Field1;
        public int Field2;
    }
    #endregion

    public static class DataCellExtension
    {
        //ConditionalWeakTable is available in .NET 4.0+
        //if you use an older .NET, you have to create your own CWT implementation (good luck with that!)
        static readonly ConditionalWeakTable<DataCell, IntObject> Flags = new ConditionalWeakTable<DataCell, IntObject>();

        public static int GetFlags(this DataCell dataCell) { return Flags.GetOrCreateValue(dataCell).Value; }

        public static void SetFlags(this DataCell dataCell, int newFlags) { Flags.GetOrCreateValue(dataCell).Value = newFlags; }

        class IntObject
        {
            public int Value;
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            var dc = new DataCell();
            dc.SetFlags(42);
            var flags = dc.GetFlags();
            Console.WriteLine(flags);
        }
    }
}

除非确实需要,否则请不要这样做.如果您有一个更干净的解决方案被该略带hacky的方法所跳过,则此代码的未来维护者可能会对您有帮助.

Please don't do this unless you really must. Future maintainers of this code may have some strong words for you if there's a cleaner solution that you skipped in favor of this slightly hacky approach.

这篇关于C#通过添加属性来扩展类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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