[英]I am getting an error "Type conflicts with the imported type
我在 C# 中创建了一个名为 Users 的 class 文件。 我想从同一个 class 文件中创建一个 class 的实例。 我认为过去能够做到这一点。 当我在这里尝试时。 我收到消息““中的用户类型”与导入的“用户”类型冲突。
是否可以在 class 文件本身中创建 class 的实例。 如果是这样,有人可以告诉我我错过了什么吗?
public class Users
{
public int ID { get; set; }
public int Cityid { get; set; }
public bool Active { get; set; }
public Users GetUserforedit(int id)
我看不出为什么你不能有一个 class 的实例方法,它返回 class 本身的一个实例,尽管将这种方法static
比实例方法更常见。
(事实上,如果你不能这样做,你将无法拥有像Clone()
这样的方法)
至于你的错误信息,有两种可能:
最明显的原因是在同一个命名空间或您正在导入的命名空间中还有另一个名为Users
的 class。 你有一个名为Users
的 web 页面吗? 您的 class 文件的另一个早期版本,也许?
另一种可能性是您的 class 不在命名空间内,这会使编译器感到困惑。 尝试将 class 包装在命名空间中,看看您现在是否至少收到一条更有用的错误消息。
我创建了一个与您的示例类似的示例,并且可以执行您想要的操作。
public class User
{
public int Id { get; set; }
public int Cityid { get; set; }
public bool Active { get; set; }
private User GetUserForEdit(int id)
{
return new User()
{
Id = id,
Active = true,
Cityid = 1
};
}
public void TestUser()
{
User user = GetUserForEdit(1); //creating an instance of a class within the class file itself.
Console.WriteLine(user.Id + " " + user.Active + " " + user.Cityid);
}
}
static void Main(string[] args)
{
User user = new User();
user.TestUser();
Console.ReadLine();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.