C#内置泛型委托:Func委托1、什么是Func委托
Func委托代表有返回类型的委托
2、Func委托定义
查看Func的定义:
using System.Runtime.CompilerServices;
namespace System
{
//
// 摘要:
// 封装⼀个⽅法,该⽅法具有两个参数,并返回由 TResult 参数指定的类型的值。
//
/
/ 参数:
// arg1:
// 此委托封装的⽅法的第⼀个参数。
//
// arg2:
// 此委托封装的⽅法的第⼆个参数。
//
// 类型参数:
// T1:
// 此委托封装的⽅法的第⼀个参数的类型。
//
/
/ T2:
// 此委托封装的⽅法的第⼆个参数的类型。
//
// TResult:
// 此委托封装的⽅法的返回值类型。
//
// 返回结果:
// 此委托封装的⽅法的返回值。
[TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")] public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
}
你会发现,Func其实就是有多个输出参数并且有返回值的delegate。
3、⽰例
Func⾄少0个输⼊参数,⾄多16个输⼊参数,根据返回值泛型返回。必须有返回值,不可void。Func<int> 表⽰没有输⼊参参,返回值为int类型的委托。
Func<object,string,int> 表⽰传⼊参数为object, string ,返回值为int类型的委托。
Func<object,string,int> 表⽰传⼊参数为object, string,返回值为int类型的委托。
Func<T1,T2,,T3,int> 表⽰传⼊参数为T1,T2,,T3(泛型),返回值为int类型的委托。
代码⽰例如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunDemo
{
class Program
{
static void Main(string[] args)
{
// ⽆参数,只要返回值
Func<int> fun1 = new Func<int>(FunWithNoPara);
int result1= fun1();
Console.WriteLine(result1);
Console.WriteLine("----------------------------");
Func<int> fun2 = delegate { return19; };
int result2 = fun2();
Console.WriteLine(result2);
Console.WriteLine("----------------------------");
Func<int> fun3 = () => { return3; };
int result3 = fun3();
Console.WriteLine(result3);
Console.WriteLine("----------------------------");
/
/有⼀个参数,⼀个返回值
Func<int, int> fun4 = new Func<int, int>(FunWithPara);
int result4 = fun4(4);
Console.WriteLine($"这⾥是⼀个参数⼀个返回值的⽅法,返回值是:{result4}");
Console.WriteLine("----------------------------");
// 使⽤委托
Func<int, string> fun5 = delegate (int i) { return i.ToString(); };
string result5 = fun5(5);
Console.WriteLine($"这⾥是⼀个参数⼀个返回值的委托,返回值是:{result5}");
Console.WriteLine("----------------------------");
// 使⽤匿名委托
Func<int, string> fun6 = (int i) =>
{
return i.ToString();
};
string result6 = fun6(6);
Console.WriteLine($"这⾥是⼀个参数⼀个返回值的匿名委托,返回值是:{result6}"); Console.WriteLine("----------------------------");
typeof array// 多个输⼊参数
Func<int, string, bool> fun7 = new Func<int, string, bool>(FunWithMultiPara);
bool result7 = fun7(2, "2");
Console.WriteLine($"这⾥是有多个输⼊参数的⽅法,返回值是:{result7}");
Console.WriteLine("----------------------------");
// 使⽤委托
Func<int, string, bool> fun8 = delegate (int i, string s)
{
return i.ToString().Equals(s) ? true : false;
};
bool result8 = fun8(2, "abc");
Console.WriteLine($"这⾥是有多个输⼊参数的委托,返回值是:{result8}");
Console.WriteLine("----------------------------");
// 使⽤匿名委托
Func<int, string, bool> fun9 = (int i, string s) =>
{
return i.ToString().Equals(s) ? true : false;
};
bool result9 = fun9(45, "ert");
Console.WriteLine($"这⾥是有多个输⼊参数的匿名委托,返回值是:{result9}");
Console.ReadKey();
}
static int FunWithNoPara()
{
return10;
}
static int FunWithPara(int i)
{
return i;
}
static bool FunWithMultiPara(int i,string s)
{
return i.ToString().Equals(s) ? true : false;
}
}
}
运⾏结果:
4、真实⽰例
在下⾯的⽰例中,利⽤Func委托封装数据库通⽤访问类。
1、定义BaseModel基类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunApplication.Model
{
public class BaseModel
{
public int Id { get; set; }
}
}
2、定义Student类继承⾃BaseModel基类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunApplication.Model
{
public class Student : BaseModel
{
public string Name { get; set; }
public int Age { get; set; }
public int Sex { get; set; }
public string Email { get; set; }
}
}
3、定义数据库访问⽅法接⼝
using FunApplication.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunApplication.IDAL
{
public interface IBaseDAL
{
T Query<T>(int id) where T : BaseModel;
List<T> QueryAll<T>() where T : BaseModel;
int Insert<T>(T t) where T : BaseModel;
int Update<T>(T t) where T : BaseModel;
int Delete<T>(int id) where T : BaseModel;
}
}
4、定义属性帮助类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace FunApplication.AttributeExtend
{
public static class AttributeHelper
{
public static string GetColumnName(this PropertyInfo prop)
{
if (prop.IsDefined(typeof(ColumnAttribute), true))
{
ColumnAttribute attribute = (ColumnAttribute)prop.GetCustomAttribute(typeof(ColumnAttribute), true);
return attribute.GetColumnName();
}
else
{
return prop.Name;
}
}
}
}
5、定义ColumnAttribute类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunApplication.AttributeExtend
{
[AttributeUsage(AttributeTargets.Property)]
public class ColumnAttribute : Attribute
{
public ColumnAttribute(string name)
{
this._Name = name;
}
private string _Name = null;
public string GetColumnName()
{
return this._Name;
}
}
}
6、定义数据库⽅法接⼝实现类
using FunApplication.IDAL;
using FunApplication.Model;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using FunApplication.AttributeExtend;
namespace FunApplication.DAL
{
public class BaseDAL : IBaseDAL
{
// 数据库链接字符串
private static string strConn = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
public int Delete<T>(int id) where T : BaseModel
{
int result = 0;
using (SqlConnection conn = new SqlConnection(strConn))
{
string strSQL = "delete from Student where Id=@Id";
SqlParameter para = new SqlParameter("Id", id);
SqlCommand command = new SqlCommand(strSQL, conn);
command.Parameters.Add(para);
conn.Open();
result = command.ExecuteNonQuery();
}
return result;
}
public int Insert<T>(T t) where T : BaseModel
{
int result = 0;
using (SqlConnection conn = new SqlConnection(strConn))
{
Type type = typeof(T);
var propArray = type.GetProperties().Where(p => p.Name != "Id");
string strSQL = "insert into Student Values (@Name,@Age,@Sex,@Email) ";
SqlCommand command = new SqlCommand(strSQL, conn);
var parameters = propArray.Select(p => new SqlParameter($"@{p.GetColumnName()}", p.GetValue(t) ?? DBNull.Value)).ToArray();
command.Parameters.AddRange(parameters);
conn.Open();
result = command.ExecuteNonQuery();
}
return result;
}
public T Query<T>(int id) where T : BaseModel
{
Type type = typeof(T);
string columnString = string.Join(",", type.GetProperties().Select(p => $"[{p.GetColumnName()}]"));
string sql = $"SELECT {columnString} FROM [{type.Name}] WHERE Id={id}";
T t = null;// (T)Activator.CreateInstance(type);
using (SqlConnection conn = new SqlConnection(strConn))
{
SqlCommand command = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader reader = command.ExecuteReader();
List<T> list = this.ReaderToList<T>(reader);
t = list.FirstOrDefault();
}
return t;
}
public List<T> QueryAll<T>() where T : BaseModel
{
Type type = typeof(T);
string columnString = string.Join(",", type.GetProperties().Select(p => $"[{p.GetColumnName()}]"));
string sql = $"SELECT {columnString} FROM [{type.Name}] ";
List<T> list = new List<T>();
using (SqlConnection conn = new SqlConnection(strConn))
{
SqlCommand command = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader reader = command.ExecuteReader();
list = this.ReaderToList<T>(reader);
}
return list;
}
public int Update<T>(T t) where T : BaseModel
{
int result = 0;
using (SqlConnection conn = new SqlConnection(strConn))
{
Type type = typeof(T);
var propArray = type.GetProperties().Where(p => p.Name != "Id");
string columnString = string.Join(",", propArray.Select(p => $"[{p.GetColumnName()}]=@{p.GetColumnName()}"));
var parameters = propArray.Select(p => new SqlParameter($"@{p.GetColumnName()}", p.GetValue(t) ?? DBNull.Value)).ToArray();
//必须参数化否则引号?或者值⾥⾯还有引号
string strSQL = $"UPDATE [{type.Name}] SET {columnString} WHERE Id={t.Id}";
SqlCommand command = new SqlCommand(strSQL, conn);
command.Parameters.AddRange(parameters);
conn.Open();
result = command.ExecuteNonQuery();
}
return result;
}
private List<T> ReaderToList<T>(SqlDataReader reader) where T : BaseModel
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论