我想允许用户使用任何标准后缀(例如TB,MB,GB)输入文件大小
我们的想法是让一个程序在文件夹超过一定大小时发出警告,其大小由用户输入的字符串决定.
.net框架中是否有任何内置允许我解析1.5TB,400GB,1.9GB和0.5KB等字符串?
@R_301_323@
这是一个简单的
Interpreter的好选择.
像这样的代码是一个简单的开始,你需要处理更多的情况,并考虑套管的差异(例如Gb vs GB).
首先是上下文和表达式的定义:
public class FileSizeContext { private string input; private long output; public FileSizeContext(string input) { this.Input = input; } public string Input { get; set; } public long Output { get; set; } } public abstract class FileSizeExpression { public abstract void Interpret(FileSizeContext value); }
然后定义终端表达式,以及所有变体:
public abstract class TerminalFileSizeExpression : FileSizeExpression { public override void Interpret(FileSizeContext value) { if(value.Input.EndsWith(this.ThisPattern())) { double amount = double.Parse(value.Input.Replace(this.ThisPattern(),String.Empty)); var fileSize = (long)(amount*1024); value.Input = String.Format("{0}{1}",fileSize,this.NextPattern()); value.Output = fileSize; } } protected abstract string ThisPattern(); protected abstract string NextPattern(); } public class KbFileSizeExpression : TerminalFileSizeExpression { protected override string ThisPattern(){return "KB";} protected override string NextPattern() { return "bytes"; } } public class MbFileSizeExpression : TerminalFileSizeExpression { protected override string ThisPattern() { return "MB"; } protected override string NextPattern() { return "KB"; } } public class GbFileSizeExpression : TerminalFileSizeExpression { protected override string ThisPattern() { return "GB"; } protected override string NextPattern() { return "MB"; } } public class TbFileSizeExpression : TerminalFileSizeExpression { protected override string ThisPattern() { return "TB"; } protected override string NextPattern() { return "GB"; } }
然后你添加一个非终端表达式(这可以完成大部分工作):
public class FileSizeParser : FileSizeExpression { private List<FileSizeExpression> expressionTree = new List<FileSizeExpression>() { new TbFileSizeExpression(),new GbFileSizeExpression(),new MbFileSizeExpression(),new KbFileSizeExpression() }; public override void Interpret(FileSizeContext value) { foreach (FileSizeExpression exp in expressionTree) { exp.Interpret(value); } } }
最后,这是一种客户端代码:
var ctx = new FileSizeContext("10Mb"); var parser = new FileSizeParser(); parser.Interpret(ctx); Console.WriteLine("{0} bytes",ctx.Output); // 10485760 bytes
实例:http://rextester.com/rundotnet?code=WMGOQ13650
编辑.从Mb改为MB(一个是官方MegaByte,另一个是MegaBit).将int更改为long以考虑大尺寸.