简体   繁体   中英

Create a generic datatype method

I have a C# application which has the two methods:

private void build_float_string() {

    float[] mData = new float[1000];
    Marshal.Copy(myPointer, mData, 0, 1000);
    mData.ToList().ForEach(i => descriptor_string.Append(string.Format("{0}, ", i.ToString())));

}

Which results in the string 1.0, 1.1, 1.2, 1.3, ... . And:

private void build_byte_string() {

    byte[] mData = new byte[1000];
    Marshal.Copy(myPointer, mData, 0, 1000);
    mData.ToList().ForEach(i => descriptor_string.Append(string.Format("{0}, ", i.ToString())));

}

Which results in the string 1, 2, 3, 4, ... .

Or whatever the data happens to be.

My question is: since these methods are identical - except for the float or byte data type, can I create a generic template method for this? I'm certain C++ can do this, but I don't know where to begin for doing this in C# .

If you dont want compiletime type safety there is also the dynamic Keyword (Assuming you are using c# 4.0 or above)

private void build_string<T>() where T : struct
{
    try
    {
        T[] mData = new T[1000];
        Marshal.Copy(myPointer,(dynamic) mData, 0, 1000);
        descriptor_string.Append(String.Join(", ", mData.Select(item=>item.ToString()));
    } 
    catch(RuntimeBinderException rbe)
    {
        // Handle case here where there is no suitable Marshal.Copy Method.
    }
}

You can use Type class, or Type Parameters, I wish this helps:

class Program
{
    static void Main(string[] args)
    {
        DateTime dtNow = DateTime.Now;
        Console.WriteLine("String of float: " + getTheString<float>(12.7f));
        Console.WriteLine("String of DateTime: " + getTheString<DateTime>(dtNow));

        Console.WriteLine("The type name for a float number: " + getTheTypeName(18.25f));
        Console.WriteLine("The type name for a DateTime object: " + getTheTypeName(dtNow));

        Console.WriteLine("the result of making an instance for a float type: " + 
            makeOneInstanceOfType(20.2f, typeof(float)));
        Console.WriteLine("the result of making an instance for a DateTime type: " +
            makeOneInstanceOfType(0, typeof(DateTime)));

        //Using GetType() instead of typeof(..)
        Console.WriteLine("the result of making an instance for a DateTime type: " +
                      makeOneInstanceOfType(0, typeof(DateTime)));

        Console.ReadLine();
    }

    //Using the Type Parameter (T) for creating instances of T which T is your type,
    //specified when calling the method
    private static string getTheString<T>(T arg)
    {
        return arg+"";
    }

    //Using Type by calling the GetType() method of the object
    private static string getTheTypeName(object arg)
    {
        return arg.GetType().FullName;
    }

    //Direct use of Type, creates a float and fills is with the value if theType is float,
    //otherwise makes an instance of theType.
    private static object makeOneInstanceOfType(float valIfFloat, Type theType)
    {
        object instance;
        if(theType.IsEquivalentTo(typeof(float)))
        {                
            instance = valIfFloat;
        }
        else
        {
            instance = Activator.CreateInstance(theType);
        }
        return instance;
    }
}

I don't think you can, because there's no generic overload for Marshal.Copy()

You could make the second part generic, however:

    static StringBuilder BuildString<T>(IEnumerable<T> array, StringBuilder sb)
    {
        return array.Aggregate(sb, (s, f) => s.Append(string.Format("{0}, ", f.ToString())));
    }

    static StringBuilder BuildString<T>(IEnumerable<T> array)
    {
        return BuildString(array, new StringBuilder());
    }

Using Aggregate is more efficient than ToList().ForEach() since the latter actually allocates an intermediate list.

private void build_the_string<T>() /* where T:struct */ {
    T[] mData = new T[1000];
    typeof(Marshal).GetMethod("Copy", BindingFlags.Static|BindingFlags.Public,
    null, new Type[] { typeof(IntPtr), // or what myPointer really is,
    typeof(T[]), typeof(Int32), typeof(Int32) }, null)
    .Invoke(null, new object[] { myPointer, mData, 0, 1000 });
    mData.ToList().ForEach(i => descriptor_string.Append(string.Format("{0}, ", i.ToString())));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM