今天在写程序时候遇到这样一个编译错误:现分享出来供大家参考:
Error Inconsistent accessibility: parameter type 'ConsoleApplication1.MyEventArgs' is less accessible than method 'ConsoleApplication1.MyNewButton.TriggerEvent(ConsoleApplication1.MyEventArgs)' C:\Documents and Settings\cc66\Desktop\Projects\ConsoleApplication1\ConsoleApplication1\MyNewButton.cs 26 21 ConsoleApplication1
下面是我的代码:
解决方法有两种:
1.提升MyEventArgs类的访问权限,即为Public;
2.移除MyNewButton类的Public标志。
Error Inconsistent accessibility: parameter type 'ConsoleApplication1.MyEventArgs' is less accessible than method 'ConsoleApplication1.MyNewButton.TriggerEvent(ConsoleApplication1.MyEventArgs)' C:\Documents and Settings\cc66\Desktop\Projects\ConsoleApplication1\ConsoleApplication1\MyNewButton.cs 26 21 ConsoleApplication1
下面是我的代码:
namespace ConsoleApplication1
{
public delegate void myDelegate(object sender,object myeventargs);
public class MyNewButton:System.Windows.Forms.Button
{
protected override void OnClick(EventArgs e)
{
MyEventArgs args = new MyEventArgs();
args.FristName = "Charles";
args.LastName = "Chen";
TriggerEvent(args);
}
public void Action()
{
OnClick(new EventArgs());
}
public event myDelegate MyDelegateEvent;
public void TriggerEvent(MyEventArgs args)
{
if (MyDelegateEvent != null)
{
MyDelegateEvent(this,args);
}
}
}
}
{
public delegate void myDelegate(object sender,object myeventargs);
public class MyNewButton:System.Windows.Forms.Button
{
protected override void OnClick(EventArgs e)
{
MyEventArgs args = new MyEventArgs();
args.FristName = "Charles";
args.LastName = "Chen";
TriggerEvent(args);
}
public void Action()
{
OnClick(new EventArgs());
}
public event myDelegate MyDelegateEvent;
public void TriggerEvent(MyEventArgs args)
{
if (MyDelegateEvent != null)
{
MyDelegateEvent(this,args);
}
}
}
}
namespace ConsoleApplication1
{
class MyEventArgs:EventArgs
{
private string firstname;
public string FristName
{
get { return firstname; }
set { firstname = value; }
}
private string lastname;
public string LastName
{
get { return lastname; }
set { lastname = value; }
}
}
}
这里是什么原因导致的编译错误呢?其实很简单,访问修饰符的问题。首先在默认情况下名称空间中的类如果没有什么修饰符,默认为internal(MyEventArgs就是这样), 那么当该类型别声明在别的名称空间中的类中时,如果该参数的方法是public, 并且该类的也是public类,那么问题就出来了(如MyNewButton类,该类可以被其他名称空间中的类引用,但是MyEventArgs类是internal, 这样就导致来MyEventArgs类限制来TriggerEvent访问权限会出现上面的编译错误)。{
class MyEventArgs:EventArgs
{
private string firstname;
public string FristName
{
get { return firstname; }
set { firstname = value; }
}
private string lastname;
public string LastName
{
get { return lastname; }
set { lastname = value; }
}
}
}
解决方法有两种:
1.提升MyEventArgs类的访问权限,即为Public;
2.移除MyNewButton类的Public标志。