当同时给出的参数无效时,接受多个参数的方法应该抛出哪个异常?
作为一个例子,考虑
public Bar DoSomething(Foo f1, Foo f2)
{
//implementation...
}
Run Code Online (Sandbox Code Playgroud)
完成操作取决于f1和之间的某种关系或相似性f2(如果是数组/集合,它们必须具有相同的大小;如果是运动员,它们必须属于同一团队/对手团队;等等)。
每个参数都是该操作的有效参数,但它们一起无效。例子:
public MatchResult PlayMatch(Player a, Player b)
{
if(a.Team == b.Team)
{
//Throw exception here, since players must be on different teams
}
//Play match, determine winner
}
Run Code Online (Sandbox Code Playgroud)
抛出一个ArgumentException似乎不正确,因为它意味着其中一个参数无效,而不是一对参数一起无效。
我正在尝试为单元测试创建一个模拟HttpContextBase.
var fakePrinciple = new GenericPrincipal(
new GenericIdentity(userId),
rolesList.ToArray());
var mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Setup(t => t.User).Returns(fakePrinciple);
HttpContextBase mockedContext = mockHttpContext.Object;
Run Code Online (Sandbox Code Playgroud)
单元测试在最后一个语句中失败
抛出异常:System.ArgumentException:无法获取StrongNameKeyPair的公钥.
System.Reflection.StrongNameKeyPair.nGetPublicKey(Boolean exported,Byte [] array,String container)System.Reflection.StrongNameKeyPair.get_PublicKey()System.AppDomain.InternalDefineDynamicAssembly(AssemblyName name,AssemblyBuilderAccess access,String dir,Evidence evidence,PermissionSet requiredPermissions,PermissionSet optionalPermissions,PermissionSet rejectedPermissions,StackCrawlMark&stackMark,IEnumerable`1 unsafeAssemblyAttributes)System.AppDomain.DefineDynamicAssembly(AssemblyName name,AssemblyBuilderAccess access)Castle.DynamicProxy.ModuleScope.CreateModule(Boolean signStrongName)Castle.DynamicProxy.ModuleScope.ObtainDynamicModuleWithStrongName()Castle.DynamicProxy.ModuleScope .ObtainDynamicModule(Boolean isStrongNamed)Castle.DynamicProxy.Generators.Emitters.ClassEmitter.CreateTypeBuilder(ModuleScope modulescope,String name,Type(blah blah snip)
我用谷歌搜索,这里的建议似乎不起作用(更改RSA文件夹安全设置等)http://groups.google.com.br/group/castle-project-users/browse_thread/thread/85685cf32a795158
我是正确地认为,因为HttpContextBase是的一部分System.Web.Abstraction,这是一个签名的程序集.Moq实际上会尝试签署动态组件,但失败了吗?
我对RegEx很新 - 所以有人可以帮我弄清楚到底出了什么问题吗?
我有这个代码:
string regPattern = "*[~#%&*{}/<>?|\"-]+*";
string replacement = "";
Regex regExPattern = new Regex(regPattern);
Run Code Online (Sandbox Code Playgroud)
然而,当我的应用程序遇到regExPattern行时,我得到一个ArgumentException - Quantifier {x,y}后面没有任何错误.
有人可以帮忙吗?
编辑:我需要将此模式传递到foreach循环,如下所示:
if (paths.Contains(regPattern))
{
foreach (string files2 in paths)
{
try
{
string filenameOnly = Path.GetFileName(files2);
string pathOnly = Path.GetDirectoryName(files2);
string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
string sanitized = Path.Combine(pathOnly, sanitizedFileName);
//write to streamwriter
System.IO.File.Move(files2, sanitized);
}
catch (Exception ex)
{
//write to streamwriter
}
}
}
else
{
//write to streamwriter
}
Run Code Online (Sandbox Code Playgroud)
如果将模式传递到此循环中,如何定义模式?
CompareTo不适合我.
我的linq查询是
var result = from c in customers
where c.CustomerID.CompareTo(txtSerchId.Text) >= 0
select` c;
Run Code Online (Sandbox Code Playgroud)
而他们得到一个例外
//////例外///////////
System.ArgumentException was caught
Message=Value does not fall within the expected range.
Run Code Online (Sandbox Code Playgroud)
我的代码是这样的
var result =
from c in customers
where c.CustomerID.CompareTo(txtSerchId.Text) >= 0
select c;
if (result != null)
{
IEnumerator<Customer> resultEnum = result.GetEnumerator();
while (resultEnum.MoveNext())
{
Customer c = (Customer)resultEnum.Current;
addToDataSet(Guid.NewGuid().ToString(), c);
}
ShowResult();
}
else
{
MessageBox.Show("No Customer found within criteria");
}
Run Code Online (Sandbox Code Playgroud)
异常就在这条线上
IEnumerator<Customer> resultEnum = result.GetEnumerator();
Run Code Online (Sandbox Code Playgroud) 我决定尝试AForge的视频和图像处理,我尝试实现这个简单的演示:
private void Main_Load(object sender, EventArgs e)
{
// enumerate video devices
FilterInfoCollection videoDevices = new FilterInfoCollection(
FilterCategory.VideoInputDevice);
// create video source
VideoCaptureDevice videoSource = new VideoCaptureDevice(
videoDevices[0].MonikerString);
// set NewFrame event handler
videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
// start the video source
videoSource.Start();
}
private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
this.pictureBox1.Image = eventArgs.Frame;
}
Run Code Online (Sandbox Code Playgroud)
问题是我总是得到一个ArgumentException,但并不总是马上发生.它弹出Application.Run(new Main());,但堆栈跟踪的顶部看起来像这样:
at System.Drawing.Image.get_Width() at System.Drawing.Image.get_Size()at System.Windows.Forms.PictureBox.ImageRectangleFromSizeMode(PictureBoxSizeMode mode)at System.Windows.Forms.PictureBox.OnPaint(PaintEventArgs pe)不确定这是否相关,但ParamName异常的属性为null.我试过在try ... catch块中包装图像赋值,但这没有帮助.我还检查过以确保图像在分配之前不为空.我还检查了非null,但是0x0大小的图像. …
我正在开发一个WPF程序,从网上获取图片并使用图像控件.我的图片列表有50张图片(来自vimeo的缩略图).一切看起来很好但是数字45.图片有一些问题,当我到达第45张图片时,我得到了这个例外:
价值不在预期范围内.
例外http://img232.imageshack.us/img232/2748/5688301315b2497090468bc.png
我用try-catch但是我抓不住它.因为它出现在Bitmap类中.以下是详细信息:
at System.Windows.Media.ColorContext.GetColorContextsHelper(GetColorContextsDelegate getColorContexts) at System.Windows.Media.Imaging.BitmapFrameDecode.get_ColorContexts() at System.Windows.Media.Imaging.BitmapImage.FinalizeCreation() at System.Windows.Media.Imaging.BitmapImage.OnDownloadCompleted(Object sender, EventArgs e) at System.Windows.Media.UniqueEventHelper.InvokeEvents(Object sender, EventArgs args) at System.Windows.Media.Imaging.LateBoundBitmapDecoder.DownloadCallback(Object arg) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler) at System.Windows.Threading.DispatcherOperation.InvokeImpl() at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Windows.Threading.DispatcherOperation.Invoke() at System.Windows.Threading.Dispatcher.ProcessQueue() at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 …
系统信息
- Windows 10技术预览版(内部版本9926)
- Visual Studio Community 2013
尝试调试:- [AT&T] Lumia 635(Windows 10技术预览版手机内置9941瓦特/ Lumia Cyan)
- [AT&T] Lumia 1520(带有Lumia Denim和PfD的Windows Phone 8.1)
- [Unlocked] BLU Win Jr(Windows Phone 8.1 with PfD)
- [Verizon] Lumia Icon(带有Lumia Denim和PfD的Windows Phone 8.1)
我试图在我的应用程序中使用位置服务.以前,我有Visual Studio抛出错误.这是一个ArgumentException带有消息" Use of undefined keyword value 1 for event TaskScheduled in async".谷歌搜索没有找到任何解决方案.
这是代码:
Geolocator Locator = new Geolocator();
Geoposition Position = await Locator.GetGeopositionAsync();
Geocoordinate Coordinate = Position.Coordinate;
Run Code Online (Sandbox Code Playgroud)
当我可以得到抛出的错误时,在上面的示例中的第2行或第3行抛出了异常.我简化了原始代码以尝试修复它,但这是原始代码:
Geolocator Locator = new Geolocator();
Geocoordinate Coordinate = (await Locator.GetGeopositionAsync()).Position.Coordinate;
Run Code Online (Sandbox Code Playgroud)
整个应用程序在调试时可以正常工作,但几乎瞬间崩溃.
这是一个Windows 8.1 Universal项目,专注于手机项目. …
c# geolocation argumentexception async-await win-universal-app
考虑我有一个类如下:
class ProductPrice
{
public string ProductName { get; set; }
public decimal RegularPrice { get; set; }
public decimal SalePrice { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我有一个这样的函数:
public decimal CalculateDiscount(ProductPrice thePriceInfo)
{
if (thePriceInfo.SalePrice > thePriceInfo.RegularPrice)
throw new ArgumentException("Sale price cannot be greater than regular price.","?????");
return (thePriceInfo.RegularPrice-thePriceInfo.SalePrice) / thePriceInfo.RegularPrice;
}
Run Code Online (Sandbox Code Playgroud)
我想知道当我调用 ArgumentException 的构造函数时,应该为 ParamName 参数(上面的 ?????? )输入什么。
我想知道在以下情况下 ParamName 的标准约定是什么:
1)导致异常的参数嵌套在一个类中(即thePriceInfo.SalePrice)
2) 异常是由于两个不同参数之间的交互造成的(在本例中 SalePrice 高于 RegularPrice)。你用逗号什么的分隔它们吗?
另外,ParamName 参数实际上用于 .NET 本身或流行的第 3 方工具中的任何内容,还是只是提供信息,供堆栈中的其他调用代码使用?
我正在使用Path.Combine,其中一个字符串包含Unicode字符.我得到{System.ArgumentException}异常; 路径中的非法字符.
根据MSDN文件路径/名称可以有unicode字符.为什么我会得到这个例外?
编辑:这是代码:
Path.Combine("C:\ PDM\Silver","Amabel Bender QQQ")
.net exception argumentexception path-combine illegal-characters
先感谢您!我正在编写一个应用程序来读取txt文件并写入Excel.从小做起我只是想读第一行.
Console.WriteLine正确输出字符串(字符之间有空格),但是当我尝试从字符串中提取字符时,我收到此错误:附加信息:索引和长度必须引用字符串中的位置.
while ((input = stream.ReadLine()) != null)
{
//ACH HEADER LINE
if (iCurRecLine == 0 && input.IndexOf(HeaderBeginKeyWord) >= 0)
{
Console.WriteLine(input);
RepDate = input.Substring(23, 6).Trim();
RecordTypeCode = input.Substring(0, 1).Trim();
PriorityCode = input.Substring(1, 2).Trim();
ImmDestination = input.Substring(3, 10).Trim();
ImmOrigin = input.Substring(13, 10).Trim();
FileCreatedDate = input.Substring(23, 6).Trim();
FileCreatedTime = input.Substring(29, 4).Trim();
FileIDModifier = input.Substring(33, 1).Trim();
RecordSize = input.Substring(34, 3).Trim();
BlockingFactor = input.Substring(37, 2).Trim();
FormatCode = input.Substring(39, 1).Trim();
Destination = input.Substring(40, 23).Trim();
Origin = input.Substring(63, 23).Trim();
ReferenceCode = input.Substring(86, 8).Trim();
...
} …Run Code Online (Sandbox Code Playgroud) c# ×8
.net ×3
exception ×3
aforge ×1
arguments ×1
async-await ×1
geolocation ×1
httpcontext ×1
image ×1
linq ×1
moq ×1
mscorlib ×1
path-combine ×1
picturebox ×1
regex ×1
strongname ×1
wpf ×1