我有如下代碼。與默認實作的介面。以及使用此界面的用戶。但出于某種原因,在開關情況下,我的代碼使用“名稱”介面的默認實作而不是類實作。我應該改變什么才能在控制臺中看到“Ben”?
namespace ConsoleApp1
{
public interface IUser
{
// Interface with default implementation
public string Name { get => "Tom"; }
}
// User using this interface
public class BenUser : IUser
{
public string Name = "Ben";
}
public static class MainClass
{
public static void ShowName(IUser user)
{
switch (user.Name)
{
case "Ben": // I expected the code to run here
Console.WriteLine("Ben");
break;
case "Tom": // But the code goes here
Console.WriteLine("Tom");
break;
}
}
static void Main()
{
// Create a user with Name "Ben"
var ben = new BenUser();
ShowName(ben); // In console i see "Tom" for some reason
}
}
}
我無法弄清楚為什么代碼會這樣。
uj5u.com熱心網友回復:
正如評論中提到的,您需要在您的類中使用相同的形狀來實作介面 - 作為具有 get 的屬性。
public interface IUser
{
// Interface with default implementation
public string Name { get => "Tom"; }
}
// User using this interface
public class BenUser : IUser
{
public string Name { get => "Ben"; }
}
public static class MainClass
{
public static void ShowName(IUser user)
{
switch (user.Name)
{
case "Ben": // I expected the code to run here
System.Console.WriteLine("Ben");
break;
case "Tom": // But the code goes here
System.Console.WriteLine("Tom");
break;
}
}
static void Main()
{
// Create a user with Name "Ben"
var ben = new BenUser();
ShowName(ben); // In console i see "Tom" for some reason
}
}
uj5u.com熱心網友回復:
這是我的編輯,以顯示更多標準做法,請通讀評論,看看是否更清楚。創建成員的標準做法是使用accesslevel Type VariableName { get; set; }
namespace ConsoleApp1
{
public interface IUser
{
//denotes that this is set by construction, cannot be set afterwards
public string Name { get; }
}
// User using this interface
public class BenUser : IUser
{
// Standard 'getter' only member with a compiled return value
public string Name
{
get
{
return "Ben";
}
}
}
public class User : IUser
{
// private settable string to use with construction
private string _name;
// constructor
public User(string userName)
{
// sets the private variable to desired value
_name = userName;
}
// public 'getter' that returns the set value
public string Name
{
get
{
return _name;
}
}
}
public static class MainClass
{
public static void ShowName(IUser user)
{
Console.WriteLine(user.Name);
}
static void Main()
{
// Create a user with static Name "Ben"
var ben = new BenUser();
ShowName(ben);
// Create a user with variable Name set as "Carl"
var carl = new User("Carl");
ShowName(carl);
}
}
}
uj5u.com熱心網友回復:
NameinIUser是一個屬性,而inName是BenUser一個欄位。當我們使用您的代碼時,user.Name它會呼叫中get定義的方法,IUser而不是從中獲取 Name 欄位的值BenUser。這是修復錯誤的示例實作。
public class BenUser : IUser
{
public string Name { get => "Ben"; }
}
我建議不要按照您的方式進行操作,因為Name識別符號已變得含糊不清
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/476526.html
下一篇:在專案層之間傳遞的結果類
