[英]How to dynamically create an instance of a class and a method?
我做了以下 class
class Country
{
public string Name { get; set; }
public int Population { get; set; }
public Country (string name, int population)
{
Name = name;
Population = population;
}
public string GetCountryInfo()
{
return "Country" + Name + " has the population of: " + Population + ".";
}
}
我想動態創建這個 class 的實例並調用該方法(再次動態)。 我怎樣才能做到這一點?
提前致謝!
答案是使用反射。 想象一下,您按如下方式實現了 ICountry:
interface ICountry
{
string GetCountryInfo();
}
您創建了另一個 Country object 類型為:
class CountryB : ICountry
{
public CountryB(string name, int population)
{
}
public string GetCountryInfo()
{
return "This is countryB";
}
}
您可以使用反射來獲取對這些對象(包括原始國家/地區)的構造函數的引用並調用它。 調用它將為您提供該 object 的新實例。
假設您在控制台應用程序中,以下將起作用; 您可以根據需要進行調整:
var countryTypes = typeof(Program).Assembly.GetTypes()
.Where(t => t.GetInterface("ICountry") != null).ToList();
countryTypes.ForEach(t => Console.WriteLine(t.Name));
var countries = countryTypes
.Select(t => t.GetConstructor(new[]{typeof(string), typeof(int)}))
.Select(t => t.Invoke(new Object []{ "help me", 911}) as dynamic)
.ToList();
countries.ForEach(t=> Console.WriteLine(t.GetCountryInfo()));
您可以在這個 dotnet fiddle 中看到一個工作版本: https://dotnetfiddle.net/DGYJBM
-艾薩克
我希望我能正確地得到你的請求。
你可以做的是提取一個接口ICountry
。 讓Country
實施ICountry
。
然后,聲明一個ICountry
類型的變量。
現在,
ICountry country;
country c = new Country(“My Imaginary Country”, 1000000);
這里有什么動態?
該接口可以由許多其他類實現。 但是,您可以聲明一個變量,並根據情況調用不同類的構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.