Home > Mobile >  How to use a variable from arbitrary type class?
How to use a variable from arbitrary type class?

Time:12-19

I have a method, which takes an array of arbitrary type. And I have an array of objects (in my case this is a class with variable). Then I put my array of objects in this method. So how can I use a variable from this object?

public class C           // This one of my classes
{
    public int I { get; set; }
}

public static void Sort<T>(T[] array, string name) // Here i put my class as argument
{
    ...
    Array.Sort<T>(array, (a, b) => a.I.CompareTo(b.I)); // Here "I" is some variable in my class, which i need to use
    ...
}

static void Main(string[] args) // Here i create an array of classes
{
    ...
    C[] classes = new C[100000];
    Sort(classes);
    ...
}

CodePudding user response:

I suggest you implement the IComparable<T> interface in your class, and you will not even need a dedicated sorting method

Please consider the following sample code

using System;
using System.Collections.Generic;

namespace Test
{
    class Comparable : IComparable<Comparable>
    {
        public int Number { get; set; }

        public int CompareTo(Comparable other)
        {
            if (other == null)
                return 1;

            return Number.CompareTo(other.Number);
        }

    }

    class Program
    {
        static void Main()
        {
            List<Comparable> comparableList = new List<Comparable>
            {
                new Comparable { Number = 75 },
                new Comparable { Number = 1 },
                new Comparable { Number = 23 }
            };

            comparableList.Sort();

            foreach (Comparable comparable in comparableList)
                Console.WriteLine(comparable.Number);
        }

    }
}

CodePudding user response:

Is this what you want?

public class C  
{
    public int I { get; set; }
}

public class CComparer : IComparer<C>
{
    public int Compare(C x, C y)
    {
        return x.I.CompareTo(y.I);
    }
}

static class Program
{
    static void Main(string[] args)
    {
        var array = new C[100];

        // Calls CComparer.Compare(x,y);
        Array.Sort(array, new CComparer());
    }
}

An alternate version is

public class C  
{
    public int I { get; set; }

    public static IComparer<C> Comparer { get; } = new CComparer();

    class CComparer : IComparer<C>
    {
        internal CComparer() { }
        public int Compare(C x, C y)
        {
            return x.I.CompareTo(y.I);
        }
    }
}

static class Program
{
    static void Main(string[] args)
    {
        var array = new C[100];

        Array.Sort(array, C.Comparer);
    }
}
  • Related