[英]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.