[英]I am getting an error "Type conflicts with the imported type
I have created a class file in C# called Users.我在 C# 中创建了一个名为 Users 的 class 文件。 I want to create an instance of a class from within the same class file.
我想从同一个 class 文件中创建一个 class 的实例。 I thought had been able to do this in the past.
我认为过去能够做到这一点。 When I try here.
当我在这里尝试时。 I get the message "The type Users in "" conflicts with the imported type "Users" in.
我收到消息““中的用户类型”与导入的“用户”类型冲突。
Is it possible to create an instance of a class within the class file itself.是否可以在 class 文件本身中创建 class 的实例。 If so, can someone tell me what I am missing?
如果是这样,有人可以告诉我我错过了什么吗?
public class Users
{
public int ID { get; set; }
public int Cityid { get; set; }
public bool Active { get; set; }
public Users GetUserforedit(int id)
I see no reason why you couldn't have an instance method of a class that returned an instance of the class itself, although it's more common to make such a method a static
method rather than an instance method.我看不出为什么你不能有一个 class 的实例方法,它返回 class 本身的一个实例,尽管将这种方法
static
比实例方法更常见。
(In fact, if you couldn't do that, you wouldn't be able to have methods like Clone()
) (事实上,如果你不能这样做,你将无法拥有像
Clone()
这样的方法)
As for your error messages, two possibilities occur:至于你的错误信息,有两种可能:
The most obvious cause would be that there's another class called Users
in either the same namespace, or a namespace you're importing.最明显的原因是在同一个命名空间或您正在导入的命名空间中还有另一个名为
Users
的 class。 Do you have a web page called Users
?你有一个名为
Users
的 web 页面吗? Another, earlier version of your class file, perhaps?您的 class 文件的另一个早期版本,也许?
The other possibility would be that your class not being within a namespace is somehow confusing the compiler.另一种可能性是您的 class 不在命名空间内,这会使编译器感到困惑。 Try wrapping the class in a namespace, and see if you now get at least a more useful error message.
尝试将 class 包装在命名空间中,看看您现在是否至少收到一条更有用的错误消息。
I created an example that is similar to your example and does what you want.我创建了一个与您的示例类似的示例,并且可以执行您想要的操作。
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.