if (ftpType == "YouTube")
{
var digitalServiceResponse = JsonConvert.DeserializeObject<YoutubeMetadataResponse>(metadataJson)。
var fileRequest = new AddDeliveryFileRequest
{
//some codeelse if (ftpType == "Flashtalking"/span>)
{
var metadata = JsonConvert.DeserializeObject<FlashtalkingMetadataResponse>(metadataJson)。
foreach (var file in metadata.FileList)
{
var fileRequest = new AddDeliveryFileRequest
{
//some codeelse if (ftpType == "Innovid"/span>)
{
var metadata = JsonConvert.DeserializeObject<InnovidMetadataResponse>(metadataJson)。
foreach (var file in metadata.FileList)
{
var fileRequest = new AddDeliveryFileRequest
{
//some codeelse[/span
{
var digitalServiceResponse = JsonConvert.DeserializeObject<SizmekMetadataResponse>(metadataJson)。
foreach (var file in digitalServiceResponse.Metadata.FileList)
{
var fileRequest = new AddDeliveryFileRequest
{
//some code
我如何在工廠方法的幫助下擺脫這些if和else if塊呢?
uj5u.com熱心網友回復:
你可以使用一個Dictionary,其中key是string,value是Action。
例如:
static void Main( string[ ] args )?
{
// Obviously replace the body of these lambdas with your
//自定義邏輯或讓它們呼叫一個私有成員方法。
var dict = new Dictionary<string, Action>
{
{ "YouTube", ( ) => { Console.WriteLine( "YouTube" ) ; }. },
{ "Flashtalking", ( ) => { Console.WriteLine( "Flashtalking" ); }. },
{ "Innvoid", ( ) => { Console.WriteLine( "innvoid" ); }, }. },
};
// This is what this would look like if you wanted to accept.
//引數。在這種情況下,每個 "行動 "都必須接受 /span>引數。
//相同數量的引數和引數型別。
var dict2 = new Dictionary< string, Action<int, string> >
{
{ "YouTube", ( num, str ) => { Console.WriteLine( "YouTube" ) ; }. },
{ "Flashtalking", ( num, str ) => { Console.WriteLine( "Flashtalking" ); }, }. },
{ "Innvoid", ( num, str ) => { Console.WriteLine( "innvoid" ); }, }. },
};
// If you want to pass an arbitrary number of parameters .
// 你可以傳遞一個物件陣列,只需要
//將元素轉換為它們的已知型別。
var dict3 = new Dictionary<string, Action<object[ ] > >
{
{ "YouTube", ( objects ) => { Console.WriteLine( $"YouTube: {( int )objects[ 0 ]}" ); }. },
{ "Flashtalking", ( objects ) => { Console.WriteLine( $"Flashtalking: {objects[ 1 ]}" ) ; } } },
{ "Innvoid", ( _ ) => { Console.WriteLine( "innvoid" ); } },
};
//然后你可以這樣使用它。
var key = "YouTube"/span>;
if ( dict.ContainsKey( key ) )
dict[ key ]( )。
// Or to pass parameters..
if ( dict2.ContainsKey( key ))
dict2[ key ]( 42, "Some string" ) 。
//或傳遞任意數量的引數和型別。
//的引數。
if ( dict3.ContainsKey( key ) )
dict3[ key ]( new object[ ] { 42, "Some string" }; "Some string"> }; //the parameters. );
}
你會想讓你的
標籤:Dictionary成為封裝的class的只讀欄位。
