简体   繁体   English

如何解决“指定的演员表无效”。 错误

[英]How to resolve the “Specified cast is not valid.” error

I have simple project, I dynamically execute a string value with C# compiler .我有一个简单的项目,我使用C# compiler动态执行string value

follow code:遵循代码:

private void btntest_Click(object sender, EventArgs e)
        {
            string code = @"
using System;
using System.Text;
using System.Data;
using System.Reflection;
using System.ComponentModel;

namespace myNameSpace
{
    public class DynamicClass
    {
        public bool myFunction(DataRow dr)
        {
            if (dr == null)
                return false;

            if (dr.Table.Columns.Contains(""Col1"")  && (bool)dr[""Col1""] == true)
                return true;
            else
                return false;
        }
    }
}
";

            Assembly asm = BuildAssembly(code);
            object instance = null;
            Type type = null;
            instance = asm.CreateInstance("myNameSpace.DynamicClass");
            type = instance.GetType();
            DataTable dt = new DataTable();
            dt.Columns.Add("Col1");
            DataRow dr = dt.NewRow();
            dr[0] = true;

            MethodInfo method = type.GetMethod("myFunction");
            object returnVal = method.Invoke(instance, new object[] { dr });
            txtError.Text = returnVal.ToString();

        }

        Assembly BuildAssembly(string code)
        {
            CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
            CompilerParameters compilerparams = new CompilerParameters();
            compilerparams.GenerateExecutable = false;
            compilerparams.GenerateInMemory = false; 

            compilerparams.ReferencedAssemblies.Add("mscorlib.dll");
            compilerparams.ReferencedAssemblies.Add("System.dll");
            compilerparams.ReferencedAssemblies.Add("System.Data.dll");
            compilerparams.ReferencedAssemblies.Add("System.Xml.dll");

            CompilerResults results = codeProvider.CompileAssemblyFromSource(compilerparams, code);
            if (results.Errors.HasErrors)
            {
                StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
                foreach (CompilerError error in results.Errors)
                {
                    errors.AppendFormat("Line {0},{1}\t: {2}\n",
                           error.Line, error.Column, error.ErrorText);
                }
                throw new Exception(errors.ToString());
            }
            else
            {
                return results.CompiledAssembly;
            }
        }

when I run the project,I get the following error:当我运行项目时,出现以下错误:

Exception has been thrown by the target of an invocation.调用的目标已引发异常。

Inner Exception内部异常

InvalidCastException: Specified cast is not valid. InvalidCastException:指定的强制转换无效。

if I remove the (bool)dr[""Col1""] == true section, it's working well.如果我删除(bool)dr[""Col1""] == true部分,它运行良好。

what assembly or namespace should be added?应该添加什么assemblynamespace

How to fix this error?如何修复此错误?

Any help is much appreciated.任何帮助深表感谢。

The problem is this line:问题是这一行:

dt.Columns.Add("Col1");

If you do not specify a type, it will default to string .如果您不指定类型,则默认为string This means that the value of the cell is getting converted to a string True .这意味着单元格的值正在转换为字符串True So you should be doing this:所以你应该这样做:

dt.Columns.Add("Col1", typeof(bool));

As you have already pointed out, this is the line causing the issue:正如您已经指出的那样,这是导致问题的行:

if (dr.Table.Columns.Contains("Col1")  && (bool)dr["Col1"] == true)

The explicit cast of dr["Col1"] to a bool is failing because the value is not a boolean .dr["Col1"]显式转换为bool失败,因为该值不是 boolean The explicit cast fails.显式转换失败。

Assuming that dr["Col1"] should actually contain a bool but may not always, you could verify it's type before converting using syntax like this:假设dr["Col1"]实际上应该包含一个bool但可能并非总是如此,您可以在使用如下语法进行转换之前验证它的类型:

dr["Col1"] is bool myValue && myValue == true

The above code verified that dr["Col1"] is a bool and then defined myValue as that bool value.上面的代码验证了dr["Col1"]是一个bool ,然后将myValue定义为该bool值。

The code can become even cleaner by removing myValue == true and just having myValue (as it will be evaluated as true or false ).通过删除myValue == true并仅使用myValue (因为它将被评估为truefalse ),代码可以变得更加清晰。 In your quoted code:在您引用的代码中:

if (dr.Table.Columns.Contains(""Col1"") && dr[""Col1""] is bool myValue && myValue)

If dr["Col1"] does not actually contain a bool but actually contains an int or something else as an indicator of the value being true you will need to implement different logic.如果dr["Col1"]实际上不包含bool但实际上包含int或其他东西作为值为 true 的指示符,则您将需要实现不同的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM