GVKun编程网logo

为什么不能在功能中使用协议“ Encodable”作为类型

21

本文的目的是介绍为什么不能在功能中使用协议“Encodable”作为类型的详细情况,我们将通过专业的研究、有关数据的分析等多种方式,同时也不会遗漏关于c#–为什么不能在迭代器上下文中使用unsafe关

本文的目的是介绍为什么不能在功能中使用协议“ Encodable”作为类型的详细情况,我们将通过专业的研究、有关数据的分析等多种方式,同时也不会遗漏关于c# – 为什么不能在迭代器上下文中使用unsafe关键字?、c# – 为什么我不能在类中使用HttpServerUtility.HtmlEncode?、c# – 动态LINQ to DataTable:为什么使用硬编码字符串“it”作为DataRow、exec为什么不能在具有子功能的功能中工作?的知识。

本文目录一览:

为什么不能在功能中使用协议“ Encodable”作为类型

为什么不能在功能中使用协议“ Encodable”作为类型

我正在尝试通过符合Encodable协议的编码模型来获取数据。但是它无法encode像下面的代码那样调用func :

// MARK: - Demo2class TestClass2: NSObject, Encodable {    var x = 1    var y = 2}var dataSource2: Encodable?dataSource2 = TestClass2()// error: `Cannot invoke ''encode'' with an argument list of type ''(Encodable)''`let _ = try JSONEncoder().encode(dataSource2!)//func encode<T>(_ value: T) throws -> Data where T : Encodable

但是在另一个演示中,效果很好,为什么呢?

// MARK: - Demo1protocol TestProtocol {    func test()}class TestClass1: NSObject, TestProtocol {    func test() {        print("1")    }    var x = 1    var y = 2}var dataSource1: TestProtocol?dataSource1 = TestClass1()func logItem(_ value: TestProtocol) {    value.test()}logItem(dataSource1!)

答案1

小编典典

解决方案1。

https://github.com/satishVekariya/SVCodable

试试这个代码,它扩展了可编码

extension Encodable {    func toJSONData() -> Data? { try? JSONEncoder().encode(self) }}

解决方案2。

避免污染带有扩展名的Apple提供的协议

protocol MyEncodable: Encodable {    func toJSONData() -> Data?}extension MyEncodable {    func toJSONData() -> Data?{ try? JSONEncoder().encode(self) }}

var dataSource2: Encodable?dataSource2 = TestClass2()let data = dataSource2?.toJSONData()

c# – 为什么不能在迭代器上下文中使用unsafe关键字?

c# – 为什么不能在迭代器上下文中使用unsafe关键字?

在看这个问题时,Jon在回答……’ How to read a text file reversly with iterator‘方面做得很好.并且有一个类似的问题,我在使用指针hocus pocus …’ .net is there a way to read a text file from bottom to top‘之前就已经关闭….

现在我开始尝试使用指针来解决这个问题,好吧,它看起来很粗糙和边缘粗糙……

public class ReadChar : IEnumerable<char>
{
    private Stream _strm = null;
    private string _str = string.Empty;
    public ReadChar(string s)
    {
        this._str = s;
    }
    public ReadChar(Stream strm)
    {
        this._strm = strm;
    }
    public IEnumerator<char> GetEnumerator()
    {
        if (this._strm != null && this._strm.CanRead && this._strm.CanSeek)
        {
            return ReverseReadStream();
        }
        if (this._str.Length > 0)
        {
            return ReverseRead();
        }
        return null;
    }

    private IEnumerator<char> ReverseReadStream()
    {
        long lIndex = this._strm.Length;
        while (lIndex != 0 && this._strm.Position != 0)
        {
            this._strm.Seek(lIndex--,SeekOrigin.End);
            int nByte = this._strm.ReadByte();
            yield return (char)nByte; 
        }
    }

    private IEnumerator<char> ReverseRead()
    {
        unsafe
        {
            fixed (char* beg = this._str)
            {
                char* p = beg + this._str.Length;
                while (p-- != beg)
                {
                    yield return *p;
                }
            }
        }
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

但发现C#编译器无法使用此实现来处理这个问题,但是当C#编译器因错误CS1629而拒绝时会被破坏 – “不安全代码可能不会出现在迭代器中”

为什么会这样?

解决方法

Eric Lippert在这里有一篇关于这个主题的优秀博客文章: Iterator Blocks,Part Six: Why no unsafe code?

c# – 为什么我不能在类中使用HttpServerUtility.HtmlEncode?

c# – 为什么我不能在类中使用HttpServerUtility.HtmlEncode?

我试图使用以下代码:
string myString = HttpServerUtility.HtmlEncode("my link & details");

我收到以下错误:

An object reference is required for the nonstatic field,method,or property.

为什么我不能在类中使用HttpServerUtility.HtmlEncode?

解决方法

HtmlEncode不是一个静态方法,需要HttpServerUtility的一个实例来调用.由于HttpContext.Current.Server是一个HttpServerUtility实例,您可以改为使用;
string myString = HttpContext.Current.Server.HtmlEncode("my link & details");

c# – 动态LINQ to DataTable:为什么使用硬编码字符串“it”作为DataRow

c# – 动态LINQ to DataTable:为什么使用硬编码字符串“it”作为DataRow

假设我有一个包含三列C1,C2,C3的DataTable:

var dt = new DataTable();
dt.Columns.Add("C1",typeof (int));
dt.Columns.Add("C2",typeof (string));
dt.Columns.Add("C3",typeof(string));

dt.Rows.Add(1,"1","1");
dt.Rows.Add(1,"2");
dt.Rows.Add(1,"2","2");

我使用Dynamic Linq on nuget到GroupBy列C1和C2,如下面的代码,它完美地工作:

var output = dt.AsEnumerable()
            .AsQueryable()
            .GroupBy("new(it[\"C1\"] as C1,it[\"C2\"] as C2)","it");

如果你注意到,它有一个硬编码字符串作为DaTarow呈现,我从以下方面得到了这个想法:

Dynamic Linq GroupBy

.如果我尝试将其更改为字符串行,例如:

GroupBy("new(row[\"C1\"] as C1,row[\"C2\"] as C2)","row");

我会得到运行时错误:

No property or field ‘row’ exists in type ‘DaTarow’

所以,我不清楚为什么要将其硬编码为DaTarow?这有什么理由吗?

解决方法

这就是Dynamic LINQ提供程序的编写方式.它有三个硬编码的关键字,它在尝试解析LINQ表达式时会识别:it,iff和new:

static readonly string keywordIt = "it";
static readonly string keywordIif = "iif";
static readonly string keywordNew = "new";

如果要查看更多详细信息,可以自行检查source到LINQ程序集.

(顺便说一句:“它”似乎是“标识符令牌”的缩写,如果我不得不猜测的话.)

exec为什么不能在具有子功能的功能中工作?

exec为什么不能在具有子功能的功能中工作?

看来您不能在具有子功能的函数中使用exec …

有人知道为什么这个Python代码不起作用吗?我在test2中的exec处出错。另外,我知道exec的风格不好,但是请相信我,出于适当的原因,我正在使用exec。否则我不会使用它。

#!/usr/bin/env python
#

def test1():
    exec('print "hi from test1"')

test1()

def test2():
    """Test with a subfunction."""
    exec('print "hi from test2"')
    def subfunction():
        return True

test2()

编辑:我将错误缩小为在子功能中具有功能。它与raise关键字无关。

关于为什么不能在功能中使用协议“ Encodable”作为类型的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于c# – 为什么不能在迭代器上下文中使用unsafe关键字?、c# – 为什么我不能在类中使用HttpServerUtility.HtmlEncode?、c# – 动态LINQ to DataTable:为什么使用硬编码字符串“it”作为DataRow、exec为什么不能在具有子功能的功能中工作?等相关内容,可以在本站寻找。

本文标签: