C #: How to declare several similar structures?

My application uses several "handles" (all IntPtr) of various types.

I want to help make sure that the correct descriptor type is passed to my various methods ... if I used IntPtr for all of them, then there is no hint that the method accepts descriptor type A or type B type.

If L was on C ++ land, I could use typedefs:

typedef uint32 HdlA;
typedef uint32 HdlB;

and now I have two types: HdlA and HdlB, both of which are shared U32 under the hood. In C ++, I could also use a macro to declare structures.

Also, for the reasons for marshaling, I need these types of values ​​... I can't use a class (naturally, if I could use a class that would allow everything).

All descriptors have essentially identical definitions:

public struct HdlA
{
    private IntPtr _h;
    public bool IsValid             get { return (_h != IntPtr.Zero);} }
    //public HdlA()                 { _h = IntPtr.Zero; } // C# disallows arg-less ctor on struct
    public HdlA(IntPtr h)           { _h = h; }
    public void Invalidate()        { _h = IntPtr.Zero; }
    public static implicit operator IntPtr(HdlA hdl)  { return hdl._h; }
}
public struct HdlB
{
    private IntPtr _h;
    public bool IsValid             get { return (_h != IntPtr.Zero);} }
    //public HdlB()                 { _h = IntPtr.Zero; } // C# disallows arg-less ctor on struct
    public HdlB(IntPtr h)           { _h = h; }
    public void Invalidate()        { _h = IntPtr.Zero; }
    public static implicit operator IntPtr(HdlB hdl)  { return hdl._h; }
}
... etc ...

, , longhand - 5 6 , , .

, -, .

, , , HdlA, HdlB .. . # .

, , : (

?

+4
3

(int Enum), , . , , Inheritance, HandleType .

, , .

+1

, .

, , . , HndlA HndlB ToHandle() , . ToHandle() , .

, .

+1

++ .

# T4 template.

, , #, # script, , # (VisualStudio, MonoDevelop, SharpDevelop, Nant), .

.tt .t4, :

<#@ template language="C#" #>
<#@ output extension=".generated.cs" #>
namespace SomeNamespace
{
<#
foreach(string name in new string[]{"HdlA", "HdlB", /*… and so on… */})
{#>
    public struct <#=name#>
    {
        private IntPtr _h;
        public bool IsValid
        {
            get { return (_h != IntPtr.Zero); }
        }
        public <#=name#>(IntPtr h)
        {
            _h = h;
        }
        public void Invalidate()
        {
            _h = IntPtr.Zero;
        }
        public static implicit operator IntPtr(<#=name#> hdl)
        {
            return hdl._h;
        }
    }
<#}#>
}

, ASP.NET, . .cs, , .cs. , , , ( ).

- , . , , , .

,

//# arg-less ctor struct

, , , , , ( [] , new blah() #). .NET , , , , , , .

0

Source: https://habr.com/ru/post/1541679/


All Articles