C#-任何类似于boost::Any的东西

本文关键字:Any C#- 类似于 boost 任何 | 更新日期: 2023-09-27 18:25:44

我有一个要求,其中:1.我需要在列表中存储任何类型的对象2.尽可能避免抛出调用

为此,我试图想出一些办法。无论我做了什么,我都无法摆脱拳击。我想知道你们中是否有人遇到过能实现这一目标的东西

除非处理小集合,否则我创建的类基本上是无用的,因为就内存和性能而言,它需要ArrayList的1.5倍。我正在努力寻找方法来提高其中至少一个(最好是性能)。

如有任何反馈,我们将不胜感激。

    public class Castable 
    {
        Object _o;
        public override bool Equals(object obj) { return base.Equals(obj); }
        public override int GetHashCode() { return base.GetHashCode(); }
        public bool Equals<T>(T obj)
        {
            T v1 = (T)this._o;
            //T v2 = obj;
            //var v2 = obj; // Convert.ChangeType(obj, obj.GetType());
            // This doesn't work.. (Cannot convert T to Castable
            //var v2 = Convert.ChangeType(this.GetType() == obj.GetType() ?  
            //((Castable)obj)._o.GetType(), obj.GetType());
            //if (((T)this._o) != obj) //<== why this doesn't work?
            //if (v1 == obj) //<== "Operator '==' cannot be applied to operands of type 'T' and 'T'"
            if(v1.Equals(obj))
            {
                return true;
            }
            return false;
        }
        public bool Equals(Castable obj)
        {
            var v = Convert.ChangeType(obj._o, obj._o.GetType());
            return Equals(v);
        }

        public static bool operator ==(Castable a, Castable b)
        {
            return a.Equals(b);
        }
        public static bool operator !=(Castable a, Castable b)
        {
            return !a.Equals(b);
        }
        #region HOW CAN WE USE GENRIC TYPE FOR == and != OPERATOR?
        public static bool operator ==(Castable a, object b)
        {
            return a.Equals(b);
        }
        public static bool operator !=(Castable a, object b)
        {
            return !a.Equals(b);
        }
        #endregion
        public void Set<T>(T t)  { _o = t; }
        public T Get<T>() { return (T)_o; }
        public static long TestLookup(IList list, int elements, int lookups)
        {
            object value;
            Stopwatch watch = new Stopwatch();
            watch.Start();
            for (long index = 0; index < lookups; ++index)
            {
                value = list[random.Next(0, elements - 1)];
            }
            watch.Stop();
            return watch.ElapsedMilliseconds;
        }
        public static long TestCompare(IList list, int elements, int lookups)
        {
            //object value;
            bool match;
            Stopwatch watch = new Stopwatch();
            watch.Start();
            for (long index = 0; index < lookups; ++index)
            {
                match = random.Next() == (int)list[random.Next(0, elements - 1)];
            }
            watch.Stop();
            return watch.ElapsedMilliseconds;
        }
        public static long TestCompareCastable(IList<Castable> list, int elements, int lookups)
        {
            //object value;
            bool match;
            Stopwatch watch = new Stopwatch();
            watch.Start();
            for (long index = 0; index < lookups; ++index)
            {
                match = list[random.Next(0, elements - 1)] == random.Next(); //most of the times 1.4 times
                //match = list[random.Next(0, elements - 1)].Equals(random.Next()); // may be 1.3 times ArrayList
            }
            watch.Stop();
            return watch.ElapsedMilliseconds;
        }

        public static void Test(int elements, int lookups, int times)
        {
            List<int> intList = new List<int>();
            List<Castable> castableList = new List<Castable>();
            ArrayList intArrayList = new ArrayList();
            if (Stopwatch.IsHighResolution)
                Console.WriteLine("We have a high resolution timer available");
            long frequency = Stopwatch.Frequency;
            Console.WriteLine(" Timer frequency in ticks per second = {0}", frequency);
            for (int index = 0; index < elements; ++index)
            {
                intList.Add(random.Next());
                intArrayList.Add(random.Next());
                Castable c = new Castable();
                c.Set(random.Next());
                castableList.Add(c);
            }
            long ms = 0;

            string result = "";
            string ratios = "";
            for (int time = 0; time < times; ++time)
            {
                ms = TestLookup(intList, elements, lookups);
                result += "intList Lookup Time " + ms.ToString() + " MS'n";
                ms = TestLookup(castableList, elements, lookups);
                result += "intArrayList Lookup Time " + ms.ToString() + " MS'n";
                ms = TestLookup(intArrayList, elements, lookups);
                result += "castableList Lookup Time " + ms.ToString() + " MS'n";
                ms = TestCompare(intList, elements, lookups);
                result += "intList Compare Time " + ms.ToString() + " MS'n";
                long msarraylist = ms = TestCompare(intArrayList, elements, lookups);
                result += "intArrayList Compare Time " + ms.ToString() + " MS'n";
                ms = TestCompareCastable(castableList, elements, lookups);
                result += "castableList Compare Time " + ms.ToString() + " MS'n";
                ratios += String.Format("round: {0}, ratio: {1}'n", time, (float)ms / msarraylist);
            }
            //MessageBox.Show(result);
            MessageBox.Show(ratios);

            int i = 10;
            Castable o1 = new Castable();
            o1.Set(i);
            int j = 10;
            Castable o2 = new Castable();
            o2.Set(j);
            if (!o1.Equals(10))
            {
                Console.WriteLine("unequal");
            }
            if (!o1.Equals(o2))
            {
                Console.WriteLine("unequal");
            }
            if (o1 != j)
            {
                Console.WriteLine("unequal");
            }
            int x = o1.Get<int>();
        }
    }

编辑

简而言之,我正在努力实现:

@winSharp93:是的,简而言之:List GenericGenericCollection=新列表()
GenericGenericCollection.Add(新字符串("一首十四行诗")
GenericGenericCollection.Add(42)
GenericGenericCollection.Add(新的MyOwnCustomType)

再次编辑

我发现了两种方法:1.在.NET 4中,引入了一个新的"dynamic"关键字。如果将Object _o;行替换为dynamic _o;,则可以按原样使用代码。问题是,尽管dynamic应该是dynamic类型,但性能就像装箱一样。。

  1. 可以通过添加隐式(我更喜欢)或显式强制转换运算符来提高性能,而不是依赖于泛型==运算符。

  2. 基于http://igoro.com/archive/fun-with-c-generics-down-casting-to-a-generic-type/我添加了以下类。这涉及到装箱和性能——下面的类性能比int或Castable的ArrayList好不了多少。当然,与List<int>相比还有很长的路要走。从我的角度来看,唯一的问题是,一旦对象被分配给普通的Any对象,就会在AnyInternal<T>中嵌入具体的类型。我也找不到方法T Get()。即使关键字动态在运行时也会失败:

Any.AnyInternal<dynamic> any = (Any.AnyInternal<dynamic>)anyInstanceContainingAnyInternalForInt;

//too bad I can't seal Any after AnyInternal<T> has derived from it.
public abstract class Any
{
    public static implicit operator int(Any any)
    {
        return Any.ToType<int>(any).Data;
    }
    public static AnyInternal<T> ToType<T>(Any any)
    {
        return ((AnyInternal<T>)any);
    }
    public class AnyInternal<T> : Any
    {
        private T _data;
        public T Data { get { return _data; } }
        public AnyInternal(T data)
        {
            _data = data;
        }
    }
}

C#-任何类似于boost::Any的东西

使用通用列表<T>(在System.Collections.Generic中),而不是ArrayList
不会对值类型进行任何装箱/取消装箱操作。