我有三個linq查詢,第一個只是得到一個裝配型別的串列,作業正常。第二個查詢我遇到了問題。它回傳0結果,我不知道為什么。
下面是我使用的第一個查詢,它被重復使用:
var types = (
from assemblies in AppDomain.CurrentDomain.GetAssemblies()
from type in assemblies.GetTypes()
select type
).ToList()。
接下來我有這樣一個查詢,它回傳0結果,我不確定為什么:
var injectors = (
from type in types
from attrs in type.GetCustomAttributes<InjectAttribute>()
select attrs
).ToList()。
第三個查詢與第二個查詢幾乎完全相同,只是它選擇了一個不同的屬性。這個作業是:
(
from type in types
from attrs in type.GetCustomAttributes<InjectableAttribute> ()
where attrs.ProvidedIn == ProvidedIn.Root
select type
).ToList().ForEach(service => {
var injector = injectors.Find(i => i.serviceType == service);
if (injector != null) {
var newService = Activator.CreateInstance(service)。
services.Add(newService)。
}
})
我不確定為什么第二個查詢有效而第三個查詢無效......
下面是我如何使用這兩個查詢的:
[]
public class Item { }
public class Test {
[Inject(typeof(Item))] Item item = null。
}
我想實作的是,在foreach回圈中,如果專案中的一個欄位有一個[Inject]屬性與一個特定型別一起使用,那么就創建一個實體,否則就不創建實體。這是為一個可重用的類別庫準備的,所以一個注入型別可能會也可能不會在消費該類別庫的專案中使用。如果它沒有被使用,我不想創建一個[Injectable]的實體。
側面說明:創建3個獨立的Linq查詢是最佳選擇,還是我可以將它們合并為一個查詢?
uj5u.com熱心網友回復:
Inject被應用于成員,而不是型別。要尋找成員具有該屬性的型別,你可以使用:
Inject。
where type.GetMembers()
.SelectAny(mi=>mi.GetCustomAttributes<InjectAttribute>())
.Any()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/310086.html
標籤:
