C# 中的正确函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16782786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Right Function in C#?
提问by Neo
In VB there is a function called Right, which returns a string containing a specified number of characters from the right side of a string.
在 VB 中有一个名为 Right 的函数,它从字符串的右侧返回一个包含指定数量字符的字符串。
Is there a similar function in C# that does the same thing?
C# 中是否有类似的函数可以做同样的事情?
Thank you.
谢谢你。
回答by Chief Wiggum
Update: As mentioned in the comments below my previous answer fails in case the string is shorter than the requested length (the Right()in VB.net does not). So I've updated it a bit.
更新:正如在下面的评论中提到的,如果字符串短于请求的长度(Right()VB.net 中没有),我之前的答案会失败。所以我更新了一点。
There is no similar method in C#, but you can add it with the following extension method which uses Substring()instead:
C# 中没有类似的方法,但您可以使用以下扩展方法添加它,该方法使用Substring():
static class Extensions
{
/// <summary>
/// Get substring of specified number of characters on the right.
/// </summary>
public static string Right(this string value, int length)
{
if (String.IsNullOrEmpty(value)) return string.Empty;
return value.Length <= length ? value : value.Substring(value.Length - length);
}
}
The method provided is copied from DotNetPearlsand you can get additional infos there.
提供的方法是从DotNetPearls复制的,您可以在那里获得其他信息。
回答by FrostyFire
There is no built in function. You will have to do just a little work. Like this:
没有内置功能。你只需要做一点工作。像这样:
public static string Right(string original, int numberCharacters)
{
return original.Substring(original.Length - numberCharacters);
}
That will return just like Rightdoes in VB.
这将像Right在 VB 中一样返回。
Hope this helps you! Code taken from: http://forums.asp.net/t/341166.aspx/1
希望这对你有帮助!代码取自:http: //forums.asp.net/t/341166.aspx/1
回答by Joel Coehoorn
You can call this function from C# by importing the Microsoft.VisualBasic namespace.
您可以通过导入 Microsoft.VisualBasic 命名空间从 C# 调用此函数。
But don't. Don't use .Right() from VB either. Using the newer .Substring()method instead.
但是不要。也不要使用来自 VB 的 .Right() 。.Substring()改用较新的方法。
回答by Keith Nicholas
you can use all the visual basic specific functions in C#
您可以使用 C# 中的所有 Visual Basic 特定功能
like this :-
像这样 :-
Microsoft.VisualBasic.Strings.Right(s, 10);
you will have to reference the Microsoft.VisualBasic Assembly as well.
您还必须参考 Microsoft.VisualBasic 程序集。

