यह सुनिश्चित नहीं है कि मैं यहां क्या कर रहा हूं। विस्तार विधि पहचाना नहीं गया है।स्ट्रिंग क्लास में एक एक्सटेंशन विधि जोड़ना - सी #
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using StringExtensions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
RunTests();
}
static void RunTests()
{
try
{
///SafeFormat
SafeFormat("Hi There");
SafeFormat("test {0}", "value");
SafeFormat("test missing second value {0} - {1}", "test1");
SafeFormat("{0}");
//regular format
RegularFormat("Hi There");
RegularFormat("test {0}", "value");
RegularFormat("test missing second value {0} - {1}", "test1");
RegularFormat("{0}");
///Fails to recognize the extension method here
string.SafeFormat("Hello");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
private static void RegularFormat(string fmt, params object[] args)
{
Console.WriteLine(String.Format(fmt, args));
}
private static void SafeFormat(string fmt, params object[] args)
{
string errorString = fmt;
try
{
errorString = String.Format(fmt, args);
}
catch (System.FormatException) { } //logging string arguments were not correct
Console.WriteLine(errorString);
}
}
}
namespace StringExtensions
{
public static class StringExtensionsClass
{
public static string SafeFormat(this string s, string fmt, params object[] args)
{
string formattedString = fmt;
try
{
formattedString = String.Format(fmt, args);
}
catch (System.FormatException) { } //logging string arguments were not correct
return formattedString;
}
}
}
शानदार। आश्चर्य है कि यह स्ट्रिंग के लिए ऐसा क्यों नहीं कर रहा था। SfeFormat()? –
इसमें स्ट्रिंग का संदर्भ नहीं है। –
@Chris: क्योंकि स्ट्रिंग प्रकार का नाम है, प्रकार का उदाहरण नहीं। ध्यान दें कि यह उदाहरण वास्तव में काम नहीं करेगा, क्योंकि SafeFormat विधि को दो स्ट्रिंग तर्कों के साथ-साथ पैरामीटर की आवश्यकता होती है। –