ASP.NET中MVC從后臺控制器傳遞數據到前臺視圖的方式_.Net教程
推薦:.net使用自定義類屬性實例一般來說,在.net中可以使用Type.GetCustomAttributes獲取類上的自定義屬性,可以使用PropertyInfo.GetCustomAttributes獲取屬性信息上的自定義屬性。 下面以定義一個簡單數據庫表的映射實體類來說明相關的使用方法,基于自定義類屬性和自定義類中的屬性的自定義屬性,
需要添加相應的命名空間:
復制代碼 代碼如下:
using System;
using System.Diagnostics;
using System.Reflection;
如果僅是獲取當前方法名,可以使用如下代碼:
代碼如下:
public static void WriteSysLog(int level, string content)
{
MethodBase mb = MethodBase.GetCurrentMethod();
string systemModule = Environment.NewLine;
systemModule += "模塊名:" + mb.Module.ToString() + Environment.NewLine;
systemModule += "命名空間名:" + mb.ReflectedType.Namespace + Environment.NewLine;
//完全限定名,包括命名空間
systemModule += "類名:" + mb.ReflectedType.FullName + Environment.NewLine;
systemModule += "方法名:" + mb.Name;
Console.WriteLine("LogDate: {0}{1}Level: {2}{1}systemModule: {3}{1}content: {4}", DateTime.Now, Environment.NewLine, level, systemModule, content);
Console.WriteLine();
}
但一般情況下是獲取此記錄日志方法的調用方,因此需要使用下面的代碼:(此方法僅為演示)
代碼如下:
public static void WriteSysLog(string content)
{
const int level = 1000;
StackTrace ss = new StackTrace(true);
//index:0為本身的方法;1為調用方法;2為其上上層,依次類推
MethodBase mb = ss.GetFrame(1).GetMethod();
StackFrame[] sfs = ss.GetFrames();
string systemModule = Environment.NewLine;
systemModule += "模塊名:" + mb.Module.ToString() + Environment.NewLine;
systemModule += "命名空間名:" + mb.DeclaringType.Namespace + Environment.NewLine;
//僅有類名
systemModule += "類名:" + mb.DeclaringType.Name + Environment.NewLine;
systemModule += "方法名:" + mb.Name;
Console.WriteLine("LogDate: {0}{1}Level: {2}{1}systemModule: {3}{1}content: {4}", DateTime.Now, Environment.NewLine, level, systemModule, content);
Console.WriteLine();
}
對于這一點兒,感覺有意思的是Main的調用方
代碼如下:
System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
通過
代碼如下:
StackTrace ss = new StackTrace(true);
StackFrame[] sfs = ss.GetFrames();
可以得知.NET程序的執行順序:
代碼如下:
System.Threading.ThreadHelper.ThreadStart()
System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
然后進入方法Main中。
另外,從 MethodBase 類 還可以獲取很多其他屬性,可以自行定位到System.Reflection.MethodBase 查看。
使用反射可以遍歷獲得類的所有屬性名,方法名,成員名,其中一個有趣的小例子:通過反射將變量值轉為變量名本身。
分享:.NET實現在網頁中預覽Office文件的3個方法近日公司要搞一個日常的文檔管理的東東,可以上傳、下載各種文件,如果是office文件呢還必須得支持預覽功能,其他的都好說但是唯獨office預覽功能比較麻煩,但是不能不做,廢話不多說了一步步來吧。分析了下網易郵箱的文件預覽功能,他用的是微軟的組件,最早叫Office
- 相關鏈接:
- 教程說明:
.Net教程-ASP.NET中MVC從后臺控制器傳遞數據到前臺視圖的方式。