c# 代码常用 2018(为自己)

 

 

////////////C#基础 Type IsAssignableFrom 类是否实现了指定的接口

using System;

 

namespace ConsoleApp

{

    public interface ISayHello

    {

        void SayHello();

    }

 

    class CapablePerson : ISayHello

    {

        public void SayHello()

        {

            throw new NotImplementedException();

        }

    }

 

    class UnachievablePerson

    {

 

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            Type tpISayHello = typeof(ISayHello);

            Type tpCapablePersonClass = typeof(CapablePerson);

            Type tpUnachievablePersonClass = typeof(UnachievablePerson);

 

            if (tpISayHello.IsAssignableFrom(tpCapablePersonClass))

            {

                Console.WriteLine(tpCapablePersonClass.Name + "实现了接口" + tpISayHello.Name);

            }

            else

            {

                Console.WriteLine(tpCapablePersonClass.Name + "没有实现接口" + tpISayHello.Name);

            }

 

            if (tpISayHello.IsAssignableFrom(tpUnachievablePersonClass))

            {

                Console.WriteLine(tpUnachievablePersonClass.Name + "实现了接口" + tpISayHello.Name);

            }

            else

            {

                Console.WriteLine(tpUnachievablePersonClass.Name + "没有实现了接口" + tpISayHello.Name);

            }

 

            Console.ReadKey();

        }

    }

}

////Result:

CapablePerson实现了接口ISayHello
UnachievablePerson没有实现了接口ISayHello

////////////////////////////////////////////////////////////////////

C# IsAssignableFrom与IsSubClassOf 判断匿名类是否继承父类

public class Dog : Animal

    {

        public string name { get; set; }

    }

    public class Animal

    {

        public string id { get; set; }

    }

 

    public class Main

    {

        public void Main()

        {

            Dog aa = new Dog { name = "狗", id = "动物" };

            CheckClass(aa);

        }

        public void CheckClass<T>(T entity)

        {

            bool re1 = typeof(Animal).IsAssignableFrom(typeof(T));

            //返回true的条件是Dog类直接或间接的实现了Animal类;

            bool re2 = typeof(T).IsSubclassOf(typeof(Animal));

            //返回true的条件是Dog类是Animal的子类

           

            var id = (entity as Animal).id;

        }

    }

///////////////////////////////////////////////////////////

 

首先说下 IsGenericType

用3个实例说明:

   typeof(DateTime).IsGenericType : false

   typeof(List<int>).IsGenericType: true

   typeof(Dictionary<,>).IsGenericType:true

类型如果是泛型则为 true

但是要注意以下情况:

T[], List[] 等等数组时, IsGenericType为False

typeof(T[]).GetElementType().IsGenericType才是True

 

接着说 IsGenericTypeDefinition

用2个实例说明:

   typeof(List<int>).IsGenericTypeDefintion : false

   typeof(List<>).IsGenericTypeDefinition :true

IsGenericTypeDefinition : 获取一个值,该值指示当前 Type 是否表示可以用来构造其他泛型类型的泛型类型定义。

也就是说表明 这个 type 是否可以用于构建泛型定义

比如 List<> 可以通过反射构建出 List,List

例子:

var typeList = typeof(List<>);       

Type typeDataList = typeList.MakeGenericType( typeof(DateTime)); //通过List<>构建出List<DateTime>

最后说下 IsGenericParameter

这个Property用于表明当前类型是一个T类型

例如:

    typeof(List<>).GetGenericArguments()

返回: new Type[]{ typeof(T) }

此时:

typeof(List<>).GetGenericArguments()

返回: new Type[]{ typeof(T) }

此时:

        typeof(T).IsGenericParameter == True

        typeof(T).GenericParameterPosition  == 0   

对比:

typeof(List<DateTime>).GetGenericArguments()

返回: new Type[]{ typeof(DateTime) }

此时:

    typeof(DateTime).IsGenericParameter  == False

    typeof(DateTime).GenericParameterPosition    : throw exception

///////////////////////////////////////////////////////////

 

////////////////////////////////////////////Dot Net 高性能代码/////////////////////////////////////////////////////////////////

C# AggressiveInlining: MethodImpl Attribute
Benchmark and test the AggressiveInlining option. Use MethodImplOptions.AggressiveInlining.
AggressiveInlining. The JIT compiler logically determines which methods to inline. But sometimes we know better than it does. With AggressiveInlining, we give the compiler a hint. We tell it that the method should be inlined.
Attribute
Optimization

Example. This example benchmarks a method with no attribute, and with AggressiveInlining. The method body contains several lines of useless code. This makes the method large in bytes, so the JIT compiler may decide not to inline it.
Benchmark
And: We apply the MethodImplOptions.AggressiveInlining option to Method2. This is an enum.

Result: We see that with no options, the method calls required seven nanoseconds each.

But: With inlining specified (with AggressiveInlining), the calls required less than one nanosecond each.

C# program that uses AggressiveInlining

using System;

using System.Diagnostics;

using System.Runtime.CompilerServices;

class Program {

const int _max = 10000000;

static void Main() {

 // ... Compile the methods.

 Method1();

Method2();

int sum = 0;

var s1 = Stopwatch.StartNew();

for (int i = 0; i < _max; i++) {

sum += Method1(); }

s1.Stop();

var s2 = Stopwatch.StartNew();

for (int i = 0; i < _max; i++) {

sum += Method2(); }

s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns"));

 Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.Read(); }

static int Method1() {

// ... No inlining suggestion.

return "one".Length + "two".Length + "three".Length + "four".Length + "five".Length + "six".Length + "seven".Length + "eight".Length + "nine".Length + "ten".Length;

}

[MethodImpl(MethodImplOptions.AggressiveInlining)]

static int Method2() {

// ... Aggressive inlining.

return "one".Length + "two".Length + "three".Length + "four".Length + "five".Length + "six".Length + "seven".Length + "eight".Length + "nine".Length + "ten".Length;

 }

}

Output

7.34 ns No options

0.32 ns MethodImplOptions.AggressiveInlining

 

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

发布了16 篇原创文章 · 获赞 44 · 访问量 38万+

猜你喜欢

转载自blog.csdn.net/Game_jqd/article/details/86711662