[英]var keyword can change a variable type to dynamic?
我有一個服務Entity1
他的名字是Entity1Service
,它包含一個方法GetBySerial
它負責從數據庫(我用取合適的文檔LiteDb ),並返回它:
public class Entity1Service
{
private readonly LiteCollection<Entity1> _entity1Collection;
private readonly LiteDatabase _db;
public Entity1Service()
{
_db = new LiteDatabase(Constants.DbFileName);
_entity1Collection = _db.GetCollection<Entity1>(nameof(Entity1));
}
public Entity1 GetBySerial(string serial)
{
var q = Query.EQ(nameof(Entity1.Serial), serial);
lock (Constants.DbLockObj)
{
return _entity1Collection.Find(q).SingleOrDefault();
}
}
}
如果我像這樣使用這種方法:
Entity1Service _entity1Service = new Entity1Service();
dynamic MyDynamic = new System.Dynamic.ExpandoObject();
MyDynamic.Serial = "serial";
var e1 = _entity1Service.GetBySerial(MyDynamic.Serial);
e1
將是一個動態變量。 但是,如果我像這樣使用它:
Entity1 e1 = _entity1Service.GetBySerial("serial");
正如預期的那樣,它的類型將是Entity1
。 我不明白為什么編譯器會這樣。
我在控制台應用程序 dotnet core v. 2.1 和 C# v. 7.3 中遇到這種行為
更新:
感謝 Jon Skeet,正如他在評論中提到的那樣,我嘗試制作一個“最小可重復示例”。 所以,在這個過程中,我發現問題的發生是因為為了簡單起見,我從代碼中刪除了一段代碼。 因此,當我將動態值作為參數傳遞給方法時,問題就會發生。 所以我編輯了第一個代碼部分。
這不是真的關於var
。 這只是顯示了在您的顯式類型代碼中已經發生的事情。 這是關於動態類型的工作原理。 幾乎任何涉及dynamic
表達式的結果都被認為是dynamic
。
所以在這段代碼中:
Entity1Service _entity1Service = new Entity1Service();
dynamic MyDynamic = new System.Dynamic.ExpandoObject();
MyDynamic.Serial = "serial";
var e1 = _entity1Service.GetBySerial(MyDynamic.Serial);
... MyDynamic.Serial
的編譯時類型是dynamic
,對_entity1Service.GetBySerial
的調用是動態綁定的,結果是dynamic
。 當您將e1
顯式鍵入為Entity1
,您實際上是在調用后添加了一個演員表。
如果您只是確保表達式中的所有內容都是靜態類型的,那么結果將具有您期望的靜態類型。 例如,您可以轉換參數:
Entity1Service _entity1Service = new Entity1Service();
dynamic MyDynamic = new System.Dynamic.ExpandoObject();
MyDynamic.Serial = "serial";
var e1 = _entity1Service.GetBySerial((string) MyDynamic.Serial);
或者您可以使用單獨的局部變量:
Entity1Service _entity1Service = new Entity1Service();
dynamic MyDynamic = new System.Dynamic.ExpandoObject();
MyDynamic.Serial = "serial";
string serial = MyDynamic.Serial;
var e1 = _entity1Service.GetBySerial(serial);
無論哪種方式, _entity1Service.GetBySerial
調用現在都是靜態綁定的——這幾乎肯定是你想要的——並且e1
的類型將是Entity1
。
var的簡要歷史;
var是在C#3.0中引入的。 其目的是“隱式”告訴編譯器變量的類型。 這意味着變量類型由編譯器在編譯時確定。
動態關鍵字更多地用於語言間字段信息。 不應該這樣。 它就像對象類型,無需強制轉換。
如果不看代碼,很難分辨。 它更多的是猜測。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.