当前位置:首页 > 开发教程 > .net教程 >

.NET重要主题总结 - 代码范例

时间:2016-06-01 09:12 来源:互联网 作者:源码搜藏 收藏

什么是代表? 委托封装方法把它作为第一类对象,当你声明代表,一类是在后台创建。 代表可以添加/代表或组播委托删除名为链接。 通过委托,您可以发送方法参数,例如: 隐藏 缩小 复制代码 public static class DeletageExample { private delegate void MyD

什么是代表?

委托封装方法把它作为第一类对象,当你声明代表,一类是在后台创建。代表可以添加/代表或组播委托删除名为链接。通过委托,您可以发送方法参数,例如:

    public static class DeletageExample
    {
        private delegate void MyDelegate(string txt); //Declare Delegate

        public static void DeletageExampleMethod()
	    {
            MyDelegate del = SendText; //Create Delegate object and assign function SendText
            del("Display this"); //Invoke Delegate function
        }

        public static void SendText(string txt)
        {
            Console.WriteLine(txt);
        }
    }

//Delegate Chaining or Multicast Delegate

public static class DeletageExample
    {
       private delegate void MyDelegate(string txt);

       public static void DeletageExampleMethod()

        {
            MyDelegate txt1 = SendText;
            MyDelegate txt2 = SendText2;
            txt1 += txt2;
            txt1("hay u");
        }

        public static void SendText(string txt)
        {
            Console.WriteLine(txt);
        }

        public static void SendText2(string txt)
        {
            Console.WriteLine(txt+" I am second delegate");
        }

    }

什么是匿名方法?

没有名字的方法,匿名方法被用来缩短而不是创建一种方法,并指派其委派代表的代码,方法体里面都可以在委托声明分配写入,使用匿名方法只是短期的替代方法,例如:

private delegate void MyDelegate(string txt);

 public static void DeletageExampleMethod()
    {
       MyDelegate txt1 = delegate(string txt) { Console.WriteLine(txt); };
       txt1("I am Anonymous method");
    }

什么是Lambda表达式?

λ表达式是用来缩短匿名方法,拉姆达运算符(=>)在更换使用代表关键字。例如

private delegate void MyDelegate(string txt);

 public static void DeletageExampleMethod()
     {
         MyDelegate txt1 =  txt => { Console.WriteLine(txt); }; //Use () for more than 
								//one input parameters
         txt1("I am Anonymous method");
     }

什么是泛型委托?

为了使代表更短的代码,并删除委托声明,行动<> Func键<>可以使用泛型委托。

  • 操作<> 没有返回类型,可能需要长达16个输入参数
  • FUNC <> 有返回类型,可能需要多达16个输入和一个返回类型
public static void DeletageExampleMethod()
    {
        Action<string> txt1 = txt => Console.WriteLine(txt);
        txt1("I don't have output ");
        Func<string, string> txt2 = txt =>
          {
             Console.WriteLine(txt);
             return "I am returning Value";
          };
     }

什么是事件?

事件是一种代表谁工作订阅/监听时尚。换句话说,事件和委托携手合作。以下是有关从银行取钱的人活动的一个非常基本的例子。对于任何类型的账户,钱应该从平衡对象中扣除发件人EventArgs的可用于确定帐户类型,并要求发送者。为了让这个例子简单,只有基本功能的实现。

class Program
{
    static void Main(string[] args)
    {
        var account1 = new AccountManagement();
        var person = new Person(account1) { Name = "John Doe" };
        account1.Winthdraw(person);
        var account2 = new AccountManagement();
        var person2 = new Person(account2) { Name = "Justin Phillip" };
        account2.Winthdraw(person2);
        Console.ReadLine();
    }
}

public class Person
{
    public string Name { get; set; }
    private AccountManagement _account;
    public Person( AccountManagement account)
    {
        _account = account;
        account.Deposithandler += account.DeductMoney; //Subscribe to Deduct Money Event
    }
}

public  class AccountManagement
{
    public delegate void DepostHandler(object sender, string eventArgs);
    public event DepostHandler Deposithandler;

    public void DeductMoney(object sender, string eventArgs)
    {
        Console.WriteLine(eventArgs + ": Money has been deducted from your account\n");
    }

    public void Winthdraw(Person person)
    {
        Console.WriteLine(person.Name+": You withdraw money");
        Deposithandler(this, person.Name);
    }
}

什么是隐式类型或var关键字?

通过隐式类型VAR关键字决定在声明和初始化的时间变量的数据类型。无功是在一些语言使用Variant数据类型不同,仍持有强类型的特点。瓦尔变量不能初始化为,因为编译器无法确定其数据类型(只引用类型变量可以声明为)。你必须需要隐式转换为空值,有一定的参考类型,例如,字符串

var accountnum = "342425756342"; //Correct, compiled as string
accountnum = 50;                 //Compiler error since it is considered as string in first statement.
var username = null;             //Compiler error, unable to determine the datatype
var username = (string)null;     //Successfully compile, string is reference.

什么是实体框架代码优先方法?

在代码优先方法,你不用担心数据库的设计/开发,首先要创建一个应用程序的设计,例如,Model类/实体,一旦你完成,你可以创建你从继承类的DbContext并创建DBSet你的模型类的。当你访问的DbContext类,并执行一些操作CRUD,数据库会自动由您在上下文构造了名称创建。查找当地的SQLExpress该数据库。

 public class Student
 {
     public Student()
     {

     }

     public int StudentID { get; set; }

     public string StudentName { get; set; }
 }

 public class Standard
 {
     public Standard()
     {

     }

     public int StandardId { get; set; }

     public string StandardName { get; set; }

     public string Description { get; set; }
 }

 public class Context : DbContext
 {
     public Context(): base("StudentDB.Test") //Database Name
     {

     }

     public DbSet<Student> Students { get; set; }

     public DbSet<Standard> Standards { get; set; }
 }

class Program
 {
     static void Main(string[] args)
     {
         using (var ctx = new Context())
         {
             var stud = new Student() { StudentName = "New Student" };
             ctx.Students.Add(stud);
             ctx.SaveChanges();
         }
     }
 }

什么是泛型?

一个简单的定义是将数据从它的type.There分离可能是你需要存储或多个类型读取数据,例如,你的情况下学生的班级,grade1学生ID只有整数和grade2学生ID应该是,这是一个愚蠢的例子,但我使用它进行概念验证。为了有效地实现类,你可以验证整数,字符串的ID,您可能需要声明两个学生类,但如果你想使用一个类grade1grade2学生,仿制药可以真正帮助您。

static void Main(string[] args)
 {
     var Grad1Student = new Student<int> {StudentName = "John", StudentId = 1};
     var Grad2Student = new Student<string> { StudentName = "John", StudentId = "R001" };
 }

 public class Student<T>
 {
     public string  StudentName { get; set; }
     public T StudentId { get; set; }
 }

以下是其中,通用类对象可以被发送到用于进一步处理的方法,例如:

static void Main(string[] args)
   {
       var Grad1Student = new Student<int> {StudentName = "John", StudentId = 1};
       var Grad2Student = new Student<string> { StudentName = "John", StudentId = "R001" };
       var print = new Print();
       print.PrintStudents(Grad1Student);
       print.PrintStudents(Grad2Student);
       Console.ReadLine();
   }

   public class Student<T>
   {
       public string  StudentName { get; set; }
       public T StudentId { get; set; }
   }

   public class Print
   {
      public void PrintStudents<T>(Student<T> student)
       {
         Console.WriteLine(student.StudentId);
       }
   }

什么是反射?

使用反射获取类,对象或组件,例如,程序集名称和版本,装配所有类名称列表的元数据,类的属性/字段和方法等,您还可以得到属性/字段的值,然后调用方法。反射与属性有助于使非常灵活的应用程序,你可以访问类,方法和在运行时调用它们,第三方组件很容易通过反射和属性进行导航下面是一个简单的例子。

static void Main(string[] args)
     {
       var assembies = Assembly.GetExecutingAssembly();
       Console.WriteLine("assembies are " + assembies.FullName);
       var classes = assembies.GetTypes();

          foreach (var classname in classes)
           {
              Console.WriteLine("Classes are: " + classname.FullName);

       foreach (var prop in classname.GetProperties())
                {
                  Console.WriteLine("\t"+ prop.Name);
                }

               foreach (var method in classname.GetMethods())
                {
                  Console.WriteLine("\t" + method.Name);
                }
          }

          var onlyattrubuteclass =

              assembies.GetTypes().Where(t => t.GetCustomAttributes<MyClassAttribute>().Any());

              foreach (var attrubteclass in onlyattrubuteclass)
              {
                Console.WriteLine("\n\nAttributed Class " + attrubteclass.FullName);
              }

          Console.ReadLine();
      }

      [AttributeUsageAttribute(AttributeTargets.Class)]
      public class MyClassAttribute : Attribute
      {

      }

      [MyClass]
      public class MyTest
      {
          public string Name { get; set; }
          public int Id { get; set; }
          public void TestMethod()
          {

          }
      }

什么是扩展方法?

扩展方法的名称代表用于扩展现有类的功能。这是一个静态不必额外关键字“扩展所需的类类型的第一个参数法这个 ”。扩展方法就像访问静态类方法有()运算符但类的对象。通常情况下,扩展方法很好用,我们没有对第三方DLL的代码,但是这种看法从因人而异。下面是扩展方法的简单例子。

class Program
   {
       static void Main(string[] args)
       {
           var test = new MyTest {Name = "John"};
           test.MyTestExtesnionMethod();
           Console.ReadLine();
       }
   }

   public class MyTest
   {
       public string Name { get; set; }
       public int Id { get; set; }
   }

   public static class ExtendMyTest
   {
       public static void MyTestExtesnionMethod(this MyTest test)
       {
           Console.WriteLine("I am extension method " + test.Name);
       }
   }

什么是动态和后期绑定?

动态是一种新型的.NET中可用的变量初始化过程中绕过编译器检查,并做它的运行时间。它更灵活,但危险,需要更仔细地使用。一个很酷的功能动态是与其他语言代码交互并执行它们,例如,例如,在PythonIron用于与Python代码交互并执行它。此外,动态可搭配ExpandoObject在.NET中可用的类,你可以声明属性和使用它们的运行时间。在ASP.NET MVC ViewBag是用来沟通控制器和视图这是一个很好的例子之间的数据动态这个简单的例子来运行通过Python代码动态如下:(获取从IronPython的的NuGet

public static void Main()
       {
           var pythonRuntime = Python.CreateRuntime();
           dynamic pythonFile = pythonRuntime.UseFile("Test.py");
           pythonFile.SayHellotoPython();
           Console.ReadLine();
       }

Python.py是:

import sys;
def SayHellotoPython();
    print "Hello I am Python"

ExpandoObject例子如下,它就像ViewBag在ASP.NET MVC:

public static void Main()
     {
        dynamic exp = new ExpandoObject();
        exp.Name = "John";
        exp.Age = 56;
        Console.WriteLine(exp.Name);
        Console.WriteLine(exp.Age);
        Console.ReadLine();
     }

什么是一个可选的参数?

可选的参数是有用的,如果你不知道或不想每次调用方法时,所有的参数发送值。这是您创建组不同的名称相同的参数单独的方法方法重载的一个很好的替代。有几件事情创建可选参数时,要记住,所需的参数应该是在开始和参数的顺序确实的事情,比如,你的方法有3个参数,第一个是必需的,另外两个是可选的,你不不想指定第二个参数值,你将有编译器错误,因为编译器将无法在参数映射,解决办法是使用在下面的示例中给定的名称参数:

public static void Main()
 {
     MyTestExample("John");
     MyTestExample("John", "Doe");
     MyTestExample("John", "Doe",40);
     MyTestExample(firstname:"John", age:67);
     Console.ReadLine();
  }

  public static void MyTestExample(string firstname,string lastname=null, int age=0)
   {
      Console.WriteLine("{0} {1} is {2} years old", firstname, lastname, age);
   }

什么是TPL(任务并行库)?

任务并行库可以被定义为旧线程执行的替代,并提供了在同一时间执行多个任务的一个简单的方法。任务本身可以被定义为基本执行过程。任务(S)可以通过任务工厂和轻松创建Task.WaitAll了WaitAny功能都有助于建立任务的层次或可说是任务阻断功能。例如停止执行,直到给定的任务(多个)功能未完成。任务可以继续意味着,如果主要任务是完成了,你可以指定子任务。如果你想完成的主要任务执行后,来执行日志,数据库中保存,等任何功能,此功能是非常有用的。下面是一个简单的例子任务ContinueWith为WaitAll

static void Main(string[] args)
  {
      var task = Task.Factory.StartNew(() =>
      MyFirtThread(1)).ContinueWith((prevtask) => ThreadCompleted("MyFirtThread"));
      var task1 = Task.Factory.StartNew(() => MySecondThread(2));
      var task2 = Task.Factory.StartNew(() => MyFirtThread(1));
      var task3 = Task.Factory.StartNew(() => MySecondThread(2));
      var tasklist = new List<Task> {task, task1, task2, task3};
      Task.WaitAll(tasklist.ToArray());
      Console.WriteLine("press enter to exit...");
      Console.ReadLine();
  }

public static void  MyFirtThread(int id)
  {
      Thread.Sleep(1500);
      Console.WriteLine("myFirtThread {0}",id);
  }

public static void MySecondThread(int id)
  {
      Console.WriteLine("mySecondThread {0}",id);
  }

public static void ThreadCompleted(string task)
  {
      Console.WriteLine(task + " completed");
  }

什么是并行循环可在任务并行库?

还有的ForEach对于在任务并行库可循环,帮助运行迭代并行,而不是作为这些任务中首先执行的第一个例子中给出的顺序执行任务了,那么任务1到任务3 的Parallel.ForParallel.ForEach自动处理为WaitAll功能,这意味着它会阻止执行,直到循环完成执行的所有迭代。下面是一个简单的例子:

static void Main(string[] args)
      {
          var intArray = new List<int> {1, 2, 3, 4, 5, 6, 7, 8, 9, 23, 5, 7, 356, 89};
          Parallel.ForEach(intArray, (i) => Console.WriteLine(i));
          Console.WriteLine("press enter to exit...");
          Console.ReadLine();
      }

什么是任务取消标记或如何取消任务?

由于任务执行的同时,也有非常有用的消除方法可用。通过TaskCancellationToken,所有任务的执行,可以停止或处理(记录,跳过任务等),如果有些异常。下面是一个简单的例子的CancellationTokenCancellationTokenSource生成令牌唯一标识任务,此令牌需要,如果要发送的参数来执行任务的方法,并检查他们的财产取消请求与否,这是很好的做法,发送取消令牌中的所有为更好的异常处理方法:

static void Main(string[] args)
  {
     var source = new CancellationTokenSource();
     var task = Task.Factory.StartNew(() => MyFirtThread(1, source.Token)).ContinueWith
     ((prevtask) => ThreadCompleted("MyFirtThread", source.Token));
     source.Cancel();
     Console.WriteLine("press enter to exit...");
     Console.ReadLine();
  }

 public static void  MyFirtThread(int id, CancellationToken token)
  {
     if (token.IsCancellationRequested)
     {
         Console.WriteLine("Thread Cancellation Requested");
         token.ThrowIfCancellationRequested();
     }

     Thread.Sleep(1500);
     Console.WriteLine("myFirtThread {0}",id);
 }

public static void ThreadCompleted(string task, CancellationToken token)
 {
     if (token.IsCancellationRequested)
      {
         Console.WriteLine("Thread Cancellation Requested");
         token.ThrowIfCancellationRequested();
      }

     Console.WriteLine(task + " completed");
 }

等待和异步是什么?

等待异步的结构与任务并行库工作,你仍然可以通过任务实现很多功能并行库(TPL)类,但等待异步确实节省了大量的代码,并有内置的功能,否则就需要更多的编码。异步关键字在方法签名中使用,只是告诉该方法应该等待关键字异步运行,无需等待的关键字,你会从编译器收到一条警告,该方法将同步运行。等待非阻塞方法执行代码。的好榜样的await异步响应的用户界面,例如在桌面应用程序中,如果主线程仍在进行中,你不能执行副操作/线程。如果你点击任何按钮,直到响应从调用方法发回你不能做别的。通过异步等待,可以继续运行子线程即使主线程运行,真正提高了用户体验。等待异步也在其他许多情况下有用,例如,要求的WebAPI,服务或任何Web应用程序等。

Windows窗体的简单例子给出如下:

public partial class Form1 : Form
  {
      public Form1()
      {
          InitializeComponent();
      }

      private void button1_Click(object sender, EventArgs e)
      {
          PrintLabel("John Doe");
      }

      private async void PrintLabel(string name)
      {
          var result = await AssignValue(name);
          label1.Text = result;
      }

      private Task<string> AssignValue(string name)
      {
         return Task.Factory.StartNew(() => GetValue(name));
      }

      private string GetValue(string name)
      {
         Thread.Sleep(2000);
         return "Hi " + name;
      }
  }

.net教程阅读排行

最新文章