自定义.ToString之类的方法? [英] Custom .ToString like method??
问题描述
嗨
假设我有一个看起来像这样的课:
Hi
Let say I have a class which looks something like this:
public class MyClass
{
public static readonly string MyObject = "Myobj.ClientName";
}
我不会深入探讨事物为何如此发展……这就是我必须努力的方向.问题是,我只需要在''.''之后加上一点,所以我使用子字符串来获取''.''之后的所有字符串.在应用程序的其他地方,整个字符串都按原样使用.
我想以一种简单的形式来做.我想做这样的事情:
I''m not going to dive into why things are the way they are... this is what I have to work with. Thing is, I need only the bit after the ''.'' so I use substring to get all string after the ''.''. In other places in the application the entire string is used as is.
I want to do this in a simpler form. I want to do something like this:
MyClass.MyObject.ToShort();
因此,它将像.ToString一样工作,并且只返回特定的内容.
如何将.ToShort添加到类中?
任何帮助将不胜感激.
感谢
So it will work a lot like .ToString and only return something specific.
How can I add .ToShort to the class??
Any help would be appreciated.
Thanks
推荐答案
由于您使用的是.NET 3.5,因此有一种方法可以创建可用于字符串的扩展方法.在您的情况下,它将类似于:
Since you are using .NET 3.5, there is a way to create extension methods that can be used against strings. In your case it would be something like:
public static string ToShort(this string s)
{
return s.Substring( 6 );
}
此处的键是参数中的this
标识符.从此 [
The key here is the this
identifier in the parameter. Code sample derived from this[^] article by Mike Gold.
嗨
您必须添加以下方法,如
Hi
you have to add following method like
public static string ToShort(string strsql)
{
return "";
}
//you can access
MyClass.ToShort(MyClass.MyObject);
是的,您可以添加ToShort,尝试对其进行编码.
如果您想
Yes you can add ToShort, try coding it.
you may also override ToString if you want to
这篇关于自定义.ToString之类的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!