CSharp: Tuples

 

        /// <summary>
        /// 使用元组(Tuples或ValueTuple
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static (int, string) GetInfo(int gid,string gname)
        {
            int id = gid;
            string name = gname;
            return (id, name);
        }
        /// <summary>
        /// AnonymousType
        /// </summary>
        /// <returns></returns>
        public static dynamic GetValuesAsDynamic(int gid, string gname)
        {
            return new { id = gid, name =gname };
        }

  

//元组Tuples
var person = ("Geovin Du", 30, "Soft Developer");
Console.WriteLine(person.Item1);

Tuple<string, int, string> persons = new Tuple<string, int, string>("Geovin Du", 30, "Soft Developer");
Console.WriteLine($"Name: {persons.Item1}, Age: {persons.Item2}, Occupation: {persons.Item3}");

//使用元组(Tuples或ValueTuple
var (gid, gname) = SortExample.GetInfo(20, "geovin");
Console.WriteLine($" id:{gid},name:{gname}");

dynamic dynamicResult=SortExample.GetValuesAsDynamic(20, "geovindu");
Console.WriteLine(dynamicResult);
Console.WriteLine(dynamicResult.GetType().GetProperty("id").GetValue(dynamicResult, null));
Console.WriteLine(dynamicResult.GetType().GetProperty("name").GetValue(dynamicResult, null));
Console.WriteLine(dynamicResult.GetType());

Stopwatch stopwatch = Stopwatch.StartNew();

Console.WriteLine(typeof(Person));
foreach (var propertyInfo in typeof(Person).GetProperties())
{
    Console.WriteLine(propertyInfo.Name);
}


var school = new
{
    Address = "Orlando",
    Contact = 1200,
    Employee = new { Id = 3, Name = "Tina" }
};

Console.WriteLine(school.Address);


dynamicResult = SortExample.GetValuesAsDynamic(30, "geovindu");

//AnonymousType another = new AnonymousType(something);
if (dynamicResult!=null)
{

    var v = dynamicResult;
    // v.id = 3;
    // v.name = "geovindu";
    Console.WriteLine(v);
   // object o = (object)v;
    //Console.WriteLine(o.ToString());

    //var d= Newtonsoft.Json.JsonConvert.DeserializeObject(dynamicResult.ToString());
    var d = JsonConvert.DeserializeObject<dynamic>("{ id: 30, name: \"geovindu\" }");


}

    stopwatch.Stop();
Console.WriteLine("Delegate: {0}ms", stopwatch.ElapsedMilliseconds);

  

posted @ 2024-05-22 19:48  ®Geovin Du Dream Park™  阅读(2)  评论(0编辑  收藏  举报