我有界面:
public interface IBag
{
public string BagName { get; }
}
和类从它继承:
public class CacheBag : IBag
{
private Dictionary<string, object> cache;
public Dictionary<string, object> Cache
{
get
{
return this.cache;
}
private set
{
this.cache = value;
}
}
public string BagName
{
get { return "CacheBag"; }
}
}
我尝试为从接口继承的类创建扩展方法:
public static object Retrieve(this IBag bag)
{
Type objType = bag.GetType();
IBag obj = null;
try
{
IsolatedStorageFile appStore = IsolatedStorageFile.GetUserStoreForApplication();
string fileName = string.Format(CultureInfo.InvariantCulture, "{0}.xml", bag.BagName);
if (appStore.FileExists(fileName))
{
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.Open, appStore))
{
using (StreamReader sr = new StreamReader(isoStream))
{
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(objType);
obj = (IBag)x.Deserialize(sr);
}
}
}
}
catch (Exception ex)
{
log.Error(ex.Message);
}
return obj;
}
}
但现在它起作用了:
UserBag users = new UserBag();
users.Retrieve();
我可以像这样调用扩展:
CacheBag.Retrieve();
我应该如何改变我的实现来实现这一目标?