using extension methods on int

后端 未结 7 1286
难免孤独
难免孤独 2021-02-19 04:10

I\'m reading about extension methods, and monkeying around with them to see how they work, and I tried this:

namespace clunk {
    public static class oog {
             


        
7条回答
  •  我在风中等你
    2021-02-19 04:54

    As others have said, there's no such thing as extension operators in C#.

    The closest you can get, running the risk of facilitating lots of nasty bugs down the line, would be with implicit conversion operators on a custom "bridge" type:

    // this works
    BoolLikeC evil = 7;
    if (evil) Console.WriteLine("7 is so true");
    
    // and this works too
    if ((BoolLikeC)7) Console.WriteLine("7 is so true");
    
    // but this still won't work, thankfully
    if (7) Console.WriteLine("7 is so true");
    
    // and neither will this
    if ((bool)7) Console.WriteLine("7 is so true");
    
    // ...
    
    public struct BoolLikeC
    {
        private readonly int _value;
        public int Value { get { return _value; } }
    
        public BoolLikeC(int value)
        {
            _value = value;
        }
    
        public static implicit operator bool(BoolLikeC x)
        {
            return (x.Value != 0);
        }
    
        public static implicit operator BoolLikeC(int x)
        {
            return new BoolLikeC(x);
        }
    }
    

提交回复
热议问题