C# Extend class by adding properties

This question already has an answer here:

  • Does C# have extension properties? 6 answers

  • 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);
            }
        }
    }
    

    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.


    Well you can certainly extend a class and only add fields/properties to it (although I'd discourage the use of public fields as per your sample). However, unless other code uses your new class, the fields won't exist in the objects created. For example, if other code has:

    DataCell cell = new DataCell();
    

    then that won't have your Field1 and Field2 fields.

    If every instance of the base class really should have these fields, you'd be better off working out how to change the base class rather than extending it.

    If you were wondering whether you could add "extension fields" in the same way as extension methods are added (eg public static void Foo(this DataCell cell) ) then no, that's not possible.


    There are two ways to add properties to an existing class

  • Add partial class , but this won't work for you because partial classes should be in the same assembly.

  • Inherit this class in a different class which as far I know would be a better solution for you.

  • And no you can't use a extension property like an extension method.

    链接地址: http://www.djcxy.com/p/96982.html

    上一篇: String.slice和String.substring有什么区别?

    下一篇: C#通过添加属性来扩展类